1

Why the following code print null , instead of "Test?

trait Testa {
  val loginurl:String
  def fun
  val x=fun
}

class Testc extends  Testa {
  val loginurl="test"
  def fun={
    println(loginurl)
    1
  }
}

object TestTrait extends App{
  val m=new Testc()
}
1

1 Answer 1

3

Variable x is initialized as part of the trait where it belongs Testa. At that moment, your Testc isn't in scope yet, therefore the method fun defined there cannot be used. But the variable is already bound to that method. Therefore, nothing will be printed when Testc is invoked.

If you change the definition of x from val x = fun to lazy val x = fun, by the way, and then invoke this variable after your object m is created, you'll see "test" printed (once). The type of x, though, will still be "Unit", as it was defined in the base trait.

trait Testa {
  val loginurl:String
  def fun
  lazy val x=fun
}

class Testc extends  Testa {
  val loginurl="test"
  def fun={
    println(loginurl)
    1
  }
}

scala> val testc = new Testc
testc: Testc = Testc@4106db23

scala> val testcx = testc.x
test
testcx: Unit = ()

scala> val testcx2 = testc.x
testcx2: Unit = ()
Sign up to request clarification or add additional context in comments.

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.