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
.
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.
A def is not a variable, it becomes a method and so does not have a type. To be able to look at its signature, you would have to convert it into a partial function or something similar to that. A val, however becomes a Function2 object. Look at some decompiled code if you want. This post is pretty helpful https://alvinalexander.com/scala/fp-book-diffs-val-def-scala-functions .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.