4

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 do I use Bar after I import Foo.Bar, do I really have to call Foo.Bar every single time?

2 Answers 2

13

Secondary constructors have outer scope to prevent you doing something silly like this:

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

where you try to pass a parameter to the constructor...after creating it in the constructor.

Unfortunately, this means that import Foo.Bar is not in scope for that line. You'll have to use the full path Foo.Bar.

For everything in the class except the additional constructors, Foo.Bar will be in scope as Bar.

Sign up to request clarification or add additional context in comments.

Comments

5

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"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.