Why does doSmth(() => s)
not compile? Why does the rest of the code output "value"? Is there a way to call the second function(with call-by-name parameter)?
object Test {
def main (args: Array[String]){
lazy val s: String = ""
doSmth(s)
doSmth("")
doSmth(() => s)
}
def doSmth(p: String): Unit = {
println("value!")
}
def doSmth(p: => String): Unit = {
println("call by name!")
}
}
The following code works and compiles as expected:
def doSmth(p: String): Unit = {
println("value!")
}
def doSmth(p: () => String): Unit = {
println("call by name!")
}
lazy val s: String = ""
doSmth(s)
doSmth("")
doSmth(() => s)
Note that if you have two versions of the method, one which is by-name and one which is by-value, there is no way for Scala to know which one you mean. Instead above, the second version of the method takes a function from unit to string.
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.