Scala - declaration of an uninitialized variable

I have a variable in one of my scala classes, the value of which is set only when a certain method is called. The value of the method parameter 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 too cumbersome ...

+4
source share
1 answer

In fact, using Option less cumbersome, since the question of whether value was initialized or not can be deduced from the value of Some or None in Option . This is more idiomatic Scala than using flags.

 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> xf(0) scala> x.value res1: Option[Int] = Some(0) scala> xf(0) Value already initialized with: 0 
+13
source

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


All Articles