supernatural
supernatural

Reputation: 1197

Difference between val and def in scala?

I am starting with scala and have this confusion in evaluation. If in val, the result is evaluated when declared then why on calling that val name it again gives me the body of the function.

scala> val pop = (x:Int,y:Int)=> println(s"$x $y is the number")
pop: (Int, Int) => Unit = <function2>

scala> pop(12,3)
12 3 is the number

scala> pop(12,3) //So is this expression evaluated again ? and if not how is it stored in the memory that if 12 and 3 will come as parameter then that value will be given back.
12 3 is the number
scala> pop
res6: (Int, Int) => Unit = <function2>
//why is it giving the body as it is already evaluated

Can a function with no parameters using val can be declared?

val som....which only prints say hello

Upvotes: 0

Views: 93

Answers (1)

Mario Galic
Mario Galic

Reputation: 48410

In Scala, function are first-class values so the value of pop is

(x:Int, y:Int) => println(s"$x $y is the number")

itself. Such a function-value might look very different from say value 42 but is nevertheless a regular value. For example, contrast the following

val i: Int = 42                   // assigning value 42 to name i
val f: Int => String = i => "foo" // assigning value `i => "foo"` to name f

It might become clearer if we desugar pop definition to

val pop: Function2[Int, Int, Unit] = new Function2[Int, Int, Unit] {
  def apply(x: Int, y: Int): Unit = println(s"$x $y is the number")
}

where we see pop is assigned an instance of Function2 class which contains an apply method. Furthermore pop(12, 3) desugars to

pop.apply(12,3)

where we see pop(12, 3) simply calls a method on Function2 class. Contrast the evaluation of pop

pop
res6: (Int, Int) => Unit = <function2>

with function application of a function instance pop points to

pop(12,3)
12 3 is the number

pop is a value definition in the sense that we cannot change the function it points to, for example,

pop = (i: Int) => i.toString // error: reassignment to val

Function with no parameters can be defined like so

val g = () => "I am function with no parameters"
g   // evaluates g
g() // applies function pointed to by g

Upvotes: 3

Related Questions