- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Abstract val initialization
Tue, 2008-12-23, 01:51
From Programming in Scala:
trait RationalTrait {
val numerArg: Int
val denomArg: Int
require(denomArg != 0)
...
}
a) ================
scala> val x = 2
x: Int = 2
scala> new RationalTrait {
val numerArg = 1 * x
val denomArg = 2 * x
}
java.lang.IllegalArgumentException: requirement failed
at scala.Predef$.require(Predef.scala:107)
at RationalTrait$class.$init$(<console>:7)
at $anon$1.<init>(<console>:7)
....
b)=============
scala> new RationalTrait {
val numerArg = 1
val denomArg = 2
}
==> no Exception
c)=============
scala> new RationalTrait {
val numerArg = 1 * 4
val denomArg = 2 * 5
}
==> no Exception
I could understand why in case a) we have an Exception because when require is called, demonArg has not yet been initialized. But why, if that's the explanation, we don't have an Exception in case b and c.
Could it be a matter of compile time (b, c) vs. runtime (a) evaluation?
Oscar
trait RationalTrait {
val numerArg: Int
val denomArg: Int
require(denomArg != 0)
...
}
a) ================
scala> val x = 2
x: Int = 2
scala> new RationalTrait {
val numerArg = 1 * x
val denomArg = 2 * x
}
java.lang.IllegalArgumentException: requirement failed
at scala.Predef$.require(Predef.scala:107)
at RationalTrait$class.$init$(<console>:7)
at $anon$1.<init>(<console>:7)
....
b)=============
scala> new RationalTrait {
val numerArg = 1
val denomArg = 2
}
==> no Exception
c)=============
scala> new RationalTrait {
val numerArg = 1 * 4
val denomArg = 2 * 5
}
==> no Exception
I could understand why in case a) we have an Exception because when require is called, demonArg has not yet been initialized. But why, if that's the explanation, we don't have an Exception in case b and c.
Could it be a matter of compile time (b, c) vs. runtime (a) evaluation?
Oscar