简体   繁体   English

带有call-by-name参数的重载函数和带有by-value参数的函数

[英]Overloading function with call-by-name parameter and function with by-value parameter

Why does doSmth(() => s) not compile? 为什么doSmth(() => s)不能编译? Why does the rest of the code output "value"? 为什么其余的代码输出“值”? Is there a way to call the second function(with call-by-name parameter)? 有没有办法调用第二个函数(使用call-by-name参数)?

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. 请注意,如果您有两个版本的方法,一个是按名称,另一个是按值,则Scala无法知道您的意思。 Instead above, the second version of the method takes a function from unit to string. 相反,上面的方法的第二个版本从单元到字符串采用函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM