Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make all values in scala object lazy with a single keyword

Or are vals in scala objects lazy by default?

Anyway, if it's necessary to declare a val in an object lazy by using lazy, is it possible to do something like

lazy object SomeObject

or (like you do in c++)

object A {
lazy:
    val a
    val b
    ...
}

Because I would like to be lazy and not have to relabel all my vals lazy val

like image 688
JasonMond Avatar asked Aug 11 '12 18:08

JasonMond


People also ask

What is lazy keyword in Scala?

Vals and Lazy vals are present in Scala. lazy keyword changes the val to get lazily initialized. Lazy initialization means that whenever an object creation seems expensive, the lazy keyword can be stick before val.

What does a lazy Val do?

A lazy val is most easily understood as a "memoized (no-arg) def". Like a def, a lazy val is not evaluated until it is invoked. But the result is saved so that subsequent invocations return the saved value. The memoized result takes up space in your data structure, like a val.

What is transient in Scala?

This is where the @transient lazy val pattern comes in. In Scala lazy val denotes a field that will only be calculated once it is accessed for the first time and is then stored for future reference. With @transient on the other hand one can denote a field that shall not be serialized.

What is lazy Val in spark?

Scala Language Var, Val, and Def Lazy val lazy val is a language feature where the initialization of a val is delayed until it is accessed for the first time.


1 Answers

To answer your first question ("are vals in scala objects lazy by default?"): No, not exactly, but the objects themselves are kind of lazy, which may be lazy enough. From 5.4 ("Object Definitions") of the Scala language specification:

Note that the value defined by an object definition is instantiated lazily. The new m$cls constructor is evaluated not at the point of the object definition, but is instead evaluated the first time m is dereferenced during execution of the program (which might be never at all).

So, for example, if we have these three objects:

object X {
  val answer = { println("Here's X's answer!"); 42 }
}

object Y {
  lazy val answer = { println("Here's Y's answer!"); 1 }
}

object Z extends App {
  println("Here we go.")
  println(X)
  println(Y)
  println(X.answer)
  println(Y.answer)
}

Then when we run Z, we see the following:

Here we go.
Here's X's answer!
X$@38d24866
Y$@f1aa6ce
42
Here's Y's answer!
1

So the val in X isn't lazy, but it's also not evaluated until the first time we use X.

like image 80
Travis Brown Avatar answered Oct 16 '22 15:10

Travis Brown