I'm a newbie in Scala and was playing around with lazy evaluation and stumbled with this problem: If I want to make the lazy evaluation of val c works, I have to write the dummy variables a and b before the declaration of c, which I consider too much boilerplate. I tried to declare a and b lazy val without an initial initialization but the compiler complains. If I write something like: lazy val c = a:Double, b:Int
doesn't work either.
Is there a way to get rid of these dummy variables? Can I refactor this code in a more elegant way?
var a = 0d; //> a : Double = 0.0
var b = 0; //> b : Int = 0
lazy val c = a / b //> c : Double = <lazy>
//some other code...
a = math.Pi
b = -1
(1 to 10).foreach(x => println(f"$x, ${x * c}%.8s"))
//> 1, -3.14159
//| 2, -6.28318
I don't see "some other code", but var is usually a bad code smell i scala. Why just don't do something like this
lazy val c = {
val a = ...
val b = ...
...computation with a & b ...
}