Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the implications of using def vs. val for constant values

What are the implications of using def vs. val in Scala to define a constant, immutable value? I obviously can write the following:

val x = 3;
def y = 4;
var a = x + y; // 7

What's the difference between those two statements? Which one performs better / is the recommended way / more idiomatic? When would I use one over the other?

like image 867
knittl Avatar asked Nov 23 '11 10:11

knittl


People also ask

What is the difference between DEF and Val in Scala?

val evaluates when defined. def evaluates on every call, so performance could be worse than val for multiple calls. You'll get the same performance with a single call. And with no calls you'll get no overhead from def , so you can define it even if you will not use it in some branches.

Why use val in Scala?

In Scala the general rule is that you should always use a val field unless there's a good reason not to. This simple rule (a) makes your code more like algebra and (b) helps get you started down the path to functional programming, where all fields are immutable.

What does def do in Scala?

def is the keyword you use to define a method, the method name is double , and the input parameter a has the type Int , which is Scala's integer data type.

What term would you use to define an object that Cannot be changed in Scala?

There are three ways of defining things in Scala: def defines a method. val defines a fixed value (which cannot be modified) var defines a variable (which can be modified)


2 Answers

Assuming these are class-level declarations:

The compiler will make a val final, which can lead to better-optimised code by the VM.

A def won't store the value in the object instance, so will save memory, but requires the method to be evaluated each time.

For the best of both worlds, make a companion object and declare constants as vals there.

i.e. instead of

class Foo {
  val MyConstant = 42
}

this:

class Foo {}

object Foo {
  val MyConstant = 42
}
like image 97
Luigi Plinge Avatar answered Oct 21 '22 11:10

Luigi Plinge


The val is evaluated once and stored in a field. The def is implemented as a method and is reevaluated each time, but does not use memory space to store the resulting value.

like image 23
Jean-Philippe Pellet Avatar answered Oct 21 '22 12:10

Jean-Philippe Pellet