I have a variable in one of my scala classes, whose value is only set for the first time upon calling a specific method. The method parameter value will be the initial value of the field. So I have this:
classX {
private var value: Int= _
private var initialised = false
def f(param: Int) {
if (!initialised){
value = param
initialised = true
}
}
}
Is there a more scala-like way to do this? Options seem a bit too cumbersome...
Actually using Option
is less cumbersome since the question of whether or not value
has been initialized can be inferred from the value of the Some
or None
in the Option
. This is more idiomatic Scala than using flags too.
class X() {
var value: Option[Int] = None
def f(param: Int) {
value match{
case None => value = Some(param)
case Some(s) => println("Value already initialized with: " + s)
}
}
}
scala> val x = new X
x: X = X@6185167b
scala> x.f(0)
scala> x.value
res1: Option[Int] = Some(0)
scala> x.f(0)
Value already initialized with: 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With