In scala, there is some call-by-name parameters:
def hello(who: => String) = println("hello, " + who)
What's the type of the parameter who
?
It shows the function on scala REPL as:
hello: (who: => String)Unit
Is the type still => String
? Is there any name for it? Or some documentation to describe the type?
Further questions raised by answer
Question 1
(When reading the spec of §3.3.1 (MethodTypes))
Method type is the type of a method, say I defined a method hello
:
def hello: String = "abc"
The type of the it can be written as: => String
, right? Although you can see the REPL response is:
scala> def hello:String = "abc"
hello: String
If I define a method which has parameters:
def goodname(name: String): String = name + "!"
What's the type of the method? It should be similar to String => String
, but not. Because it's a method type, and String => String
is a function type.
Question 2
(When reading the spec of §3.3.1 (MethodTypes))
I can understand this as:
def goodname(name: String): String = name + "!"
def print(f: String => String) = println(f("abc"))
print(goodname)
When I call print(goodname)
, the type of goodname
will be converted to the function type String => String
, right?
But for paramless method:
def hello: String = "abc"
What function type can it be converted? I tried:
def print(f: () => String) = println(f())
But this can't be compiled:
print(hello)
The error is:
error: type mismatch; found : String required: () => String
Could you give me an example that works?
Question 3
(When reading the spec of §6.26.2 (MethodConversions))
This Evaluation conversion is only happened when the type is not applied to argument. So, for code:
def myname:String = "abc"
def print(name: => String) = println(name)
print(myname)
My question is, when I call print(myname)
, is there conversion(I mean Evaluation conversion
) happened? I guess, since the type of myname
is just => String
, so it can be passed to print
directly.
If the print
method has changed:
def myname:String = "abc"
def print(name: String) = println(name)
print(myname)
Here the Evaluation conversion
is definitely happened, right?(From => String
to String
)