How to initialize the vals attribute in subtrait?

I tried using abstract valin a tag to initialize another value. I have received NullPointerException. I threw the behavior back to the minimum test case:

trait MessagePrinter {
  val message: String
  println(message)
}

class HelloPrinter extends MessagePrinter {
  val message = "Hello World"
}

val obj = new HelloPrinter()
println(obj.message)

This small program gives the following result:

null
Hello World

I got the impression that the shaft will never change. Is this the expected behavior or is it a compiler error? How can I get around this problem and print Hello Worldduring initialization?

+4
source share
2 answers

5.1 Scala, . vals , . def, :

trait MessagePrinter {
   def message: String
   println(message)
}

class HelloPrinter extends MessagePrinter {
   def message = "Hello World"
}

, :

class HelloPrinter extends { val message = "Hello World" } with MessagePrinter 

, MessagePrinter .

+11

def .

, , - Scala Puzzlers" Puzzler 4:

vals:

  • .
  • , .
  • val , .
  • val, val .
+3

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


All Articles