在 Scala 中,有没有办法指定函数应该声明默认参数值?
例如,在下面的代码中,有没有办法在签名中指定indirectHelloName所提供的函数必须为第二个参数提供默认值?
def helloName(name: String, greating: String = "hello"): Unit = {
println(s"$greating $name")
}
def indirectHelloName(name: String, function: (String,String) => Unit): Unit = {
if (name == "Ted") {
function(name, "Custom Greeting for Ted!")
} else {
function(name) //This would use the default value for the second argument.
}
}
Run Code Online (Sandbox Code Playgroud)
\n\n\n在 Scala 中,有没有办法指定函数应该声明默认参数值?
\n\n例如,在下面的代码中,有没有办法在签名中指定所
\nindirectHelloName提供的函数必须为第二个参数提供默认值?
函数不能有带有默认参数的可选参数,因此无法指定一个:
\n\nval f = (a: Int, b: Int) => a + b\n//\xe2\x87\x92 f: (Int, Int) => Int = $$Lambda$1073/0x000000080070c840@6cd98a05\n\nval g = (a: Int, b: Int = 5) => a + b\n// <console>:1: error: ')' expected but '=' found.\n// val g = (a: Int, b: Int = 5) => a + b\n// ^\n\nval h = new Function2[Int, Int, Int] { \n override def apply(a: Int, b: Int) = a + b\n}\n//\xe2\x87\x92 h: (Int, Int) => Int = <function2>\n\nval i = new Function2[Int, Int, Int] {\n override def apply(a: Int, b: Int = 5) = a + b\n}\n//\xe2\x87\x92 i: (Int, Int) => Int{def apply$default$2: Int @scala.annotation.unchecked.uncheckedVariance} = <function2>\n\ni(3, 5)\n//\xe2\x87\x92 res: Int = 8\n\ni(3)\n// <console>:13: error: not enough arguments for method apply: (v1: Int, v2: Int)Int in trait Function2.\n// Unspecified value parameter v2.\n// h(3)\n// ^\nRun Code Online (Sandbox Code Playgroud)\n