Scala - application-specific multiple inheritance

Consider two features: TestTrait1 and TestTrait and assume that NewObject extends both. The idea is to use a variable in TestTrait1 in TestTrait. The code below works fine.

scala> trait TestTrait1 {
 | val arguments1: Array[String] = Array("1","2")
 | }

defined trait TestTrait1

scala> trait TestTrait {
 | val arguments: Array[String]
 | val len = arguments.length
 | }

defined trait TestTrait

scala> object NewObject extends TestTrait1 with TestTrait {
 |  lazy val arguments = arguments1
 | }

defined object NewObject

scala> NewObject
res30: NewObject.type = NewObject$@7c013560

Now replace TestTrait1 with App. Since the arguments are given for a lazy evaluation, I will assume that even in the case of DelayedInit below the code will work.

scala> object NewObject extends App with TestTrait {
 | lazy val arguments = args
 | }

But this is not so. What is the reason for this?

scala> NewObject
java.lang.NullPointerException
at TestTrait$class.$init$(<console>:12)
... 35 elided

If so, then what is the decision to use args in another tag like TestTrait here?

+4
source share
1 answer
trait TestTrait1 {
  val arguments1: Array[String] = Array("1","2")
}

trait TestTrait {
  val arguments: Array[String]
  val len = arguments.length
}

, TestTrait len, . args def App, null. len lazy val def, NPE.

REPL:

scala> :paste
// Entering paste mode (ctrl-D to finish)

trait TestTrait {
  def arguments: Array[String]
  lazy val len = arguments.length
}

object NewObject extends App with TestTrait {
  override lazy val arguments = super.args // Added `override` and `super` just for clarity.
}

// Exiting paste mode, now interpreting.

defined trait TestTrait
defined object NewObject

scala> NewObject
res0: NewObject.type = NewObject$@5ace1ed4

scala> NewObject.arguments
res1: Array[String] = null

, len, :

scala> NewObject.len
java.lang.NullPointerException
  at TestTrait$class.len(<console>:12)
  at NewObject$.len$lzycompute(<console>:15)
  at NewObject$.len(<console>:15)
  ... 33 elided

, : len lazy val, def, NewObject. NewObject a class trait, , / len, NPE.

+2

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


All Articles