scalacallbynamepass-by-name

by value & by name in scala => one to one correspondence


if when calling by-value

val f: (Int) => Int = {(i) => {i * i}} # f: Int => Int = <function1>
is the shorthand for
val f: Function1[Int, Int] = {(i) => {i * i}} # f: Int => Int = <function1>

then when calling by-name
val f: (=> Int) => Int = {(i) => {i * i}} # f: (=> Int) => Int = <function1>
is the shorthand for
? what ?

and if

when calling by-value

val f = {(i) => {i * i}}:(Int) => Int # f: Int => Int = <function1>
is the shorthand for
val f = {(i) => {i * i}}:Function1[Int, Int] # f: Int => Int = <function1>

then when calling by-name
val f = {(i) => {i * i}}:(=>Int) => Int # f: (=> Int) => Int = <function1>
is the shorthand for
? what ?

in other words

if (Int) => Int is shorthand for Function1[Int, Int]

then (=> Int) => Int is shorthand for ? what ?

Thank you !


Solution

  • It isn't shorthand for anything. By-name types are by-name types. See SLS 4.6.1, http://www.scala-lang.org/files/archive/spec/2.11/04-basic-declarations-and-definitions.html#by-name-parameters.

    It is true that if you look at the resulting bytecode, you will see that the argument will be passed as a Function0, but that's a bytecode-level implementation detail. At the language level, by-name types aren't just syntactic sugar. They are actual types (though they can only appear as parameter types, not in other contexts).

    See also: Use of Scala by-name parameters