Search code examples
scalanullpointerexceptionrequiretraitsillegalargumentexception

Preconditioning (require) an uninitialized value's property in a Scala trait


Given the below trait, instance a throws NullPointerException:

trait T {
  val l: List[Int]

  require(l.size > 1)
}

case class A(list: List[Int]) extends T {
  override val l: List[Int] = list
}

val a = A(List(1,2))

Based on this StackOverflow post, I tried the below variations for T:

trait T {
  def l(): List[Int]

  require(l().size > 1)
}

trait T {
  val l: List[Int]
  lazy val s: Int = l.size

  require(s > 1)
}

trait T {
  val l: List[Int]
  def s: Int = l.size

  require(s > 1)
}

but all of them gives NullPointerException.

Is there a way to use precondition (require clause) for an uninitialized value's property in a trait or do I have to copy the precondition(s) to all classes implementing the trait?


Solution

  • You can easily do this as follow:

    scala> :paste
    // Entering paste mode (ctrl-D to finish)
    
    trait T {
      def l: List[Int]
      require(l.size > 1)
    }
    
    case class A(l: List[Int]) extends T
    
    val a = A(List(1,2))
    
    
    // Exiting paste mode, now interpreting.
    
    defined trait T
    defined class A
    a: A = A(List(1, 2))