Scala using a final static variable

class Foo(bar: String) { import Foo.Bar def this() = this(Bar) // this line fails, it seems I can only do // def this() = this(Foo.Bar) } object Foo { val Bar = "Hello Bar" } 

Basically, how can I use Bar after I import Foo.Bar , do I really need to call Foo.Bar every time?

+4
source share
2 answers

Secondary constructors have external scope so you don't do something stupid:

 class Silly(foo: String) { val bar = 123 def this() = this(bar.toString) } 

where are you trying to pass the parameter to the constructor ... after creating it in the constructor.

Unfortunately, this means that import Foo.Bar not suitable for this line. You will need to use the full path of Foo.Bar .

For the entire class, except for additional constructors, Foo.Bar will be in the form of Bar .

+13
source

What if you just import outside the class definition?

 import Foo.Bar class Foo(bar: String) { def this() = this(Bar) } object Foo { val Bar = "Hello Bar" } 
+5
source

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


All Articles