Lazy statements in tag

I find that sometimes I want to write an arbitrary statement in a tag or in another place where the thing I want to make a statement is not yet fully defined.

trait Foo {
  val aList: List[String]
  val anotherList: List[String]

  def printPairs = aList.zip(anotherList).foreach(println)

  assert(aList.size == anotherList.size) // NullPointerException, because these references are undefined right now.
}

I assume that the generalization of what I'm looking for is a hook that (always) fires after I have fully defined and instantiated the class, since this is the type of check that I usually added to the constructor.

+4
source share
1 answer

You can do this with early definitions (find it in the Scala Reference Language for more information) - with your dash exactly as you wrote it, you can expand it as follows:

class Bar(l1: List[String], l2: List[String]) extends {
  val aList = l1
  val anotherList = l2
} with Foo

assert, :

new Bar(List("a", "b"), List("c", "d")) // built successfully
new Bar(List("a", "b"), List("c", "d", "e")) // throws exception

, , ( "", ), , "", , .

+1

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


All Articles