Scala top-level package object

Edited this question to be more clear, see comments below for an explanation.

So this seems obvious to me, but it seems like it is not, but if I have a scala package object and it is at the top level of my packages. Say like com.company and this is something simple as below

 package com package object company{ val something = "Hello world." } 

Now it seemed to me that this variable would flow down and be accessible from it by child packages, but this is not so.

 // 2 Layers down instead of the direct child package com.company.app import com.company._ object Model extends App { println(something) } 

It seems that this only works with import, and that’s fine, but I was hoping that with the package object I could define top-level things for the whole package and it seeps down, but isn't it? Is there any way to do this? I appreciate any understanding of this.

+5
source share
1 answer

The code provided in your question works because it is not imported. If you want the definitions of all package objects above your current package to leak, you will have to change the package statement for classes in subpackages

An object

 package com package object company { val something = "Hello world." } 

The class in the com.company.model subpackage

 package com package company package model // package com.company.model would not work here! object Model extends App { println(something) } 

This method is often used in the scala library itself. See For example, the package statement in sciHashSet :

 package scala package collection package immutable 
+3
source

Source: https://habr.com/ru/post/1236338/


All Articles