0

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
carlos_lm
  • 523
  • 2
  • 5
  • 10

2 Answers2

6

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 ...
}
Eugene Zhulenev
  • 9,714
  • 2
  • 30
  • 40
2

Turn your statement block into a template.

scala> :pa
// Entering paste mode (ctrl-D to finish)

class X {
lazy val c = a / b
//stuff
val a = math.Pi
val b = -1
(1 to 10).foreach(x => println(f"$x, ${x * c}%.8s"))
}

// Exiting paste mode, now interpreting.

defined class X

scala> new X
1, -3.14159
2, -6.28318
3, -9.42477
4, -12.5663
5, -15.7079
6, -18.8495
7, -21.9911
8, -25.1327
9, -28.2743
10, -31.4159
res0: X = X@61c4eee0
som-snytt
  • 39,429
  • 2
  • 47
  • 129