1

I wrote this is Scala Repl

def sum(a: Int, b: Int) = a + b

This is evaluated as sum: (a: Int, b: Int)Int in Repl. def in Scala is lazily evaluated. So, what is the type that Repl displays? Also, how is this eagerly evaluated when sum(1,2) is called or how is (a: Int, b: Int)Int evaluated to Int?

I noticed this when I was playing with val in Scala. If I write val sum = (a: Int, b: Int) = a + b this is eagerly evaluated into (Int, Int) => Int = <function2> which is fine as the apply function call is made. But I don't understand what happens in case of def.

KAY_YAK
  • 191
  • 10

1 Answers1

4

The sum: (a: Int, b: Int)Int displayed by the REPL is a bit of compiler internals leaking to the userland.

sum is a method, so there is no actual value of type (a: Int, b: Int)Int, but the compiler internally associates sum with something called method type - it's a type that holds method signature - its parameter names and types + result type. This type exists only in the compiler and cannot be directly written in Scala code.

ghik
  • 10,706
  • 1
  • 37
  • 50
  • As a minor caveat: method types are described in the language specification (https://www.scala-lang.org/files/archive/spec/2.13/03-types.html#method-types), they aren't just compiler internals. – Alexey Romanov Nov 12 '19 at 21:44