AnhMV
AnhMV

Reputation: 11

Declare variable in Scala

I just new in Scala, I know Scala have three keywords to declare variables is:

def defines a method
val defines a fixed value (which cannot be modified)
var defines a variable (which can be modified)

I am going to write some code to test with an anonymous method.

object Anonymous {
  def main(args: Array[String]): Unit = {
    def double_1 = (i: Int) => { i * 2 }
    val double_2 = (i: Int) => { i * 2 }
    var double_3 = (i: Int) => { i * 2 }
    println(double_1(2))
    println(double_2(2))
    println(double_3(2))
  }
}

Thanks!

Upvotes: 0

Views: 273

Answers (1)

jwvh
jwvh

Reputation: 51271

First off, they are not anonymous methods. They are functions and they each have a name so they are not anonymous.

The main difference between them is that double_3 can be reassigned to some different function value.

var double_3 = (i: Int) => { i * 2 }
double_3 = (i: Int) => i + 3  // the compiler allows this

The others cannot.

It would be rather unusual to defined a function as a def. def is mostly used to declare methods because a def is re-evaluated every time it is referenced.

def x = 3 + 4
val y = 3 + 4

Both x and y evaluate to 7, but the addition is redone every time x is referenced. For y the addition is done once, at the definition, and never again.

Upvotes: 1

Related Questions