>我有以下方法:
scala> def method_with_default(x: String = "default") = {x + "!"}
method_with_default: (x: String)java.lang.String
scala> method_with_default()
res5: java.lang.String = default!
scala> method_with_default("value")
res6: java.lang.String = value!
我正在尝试使用 val 实现相同的目标,但我收到语法错误,如下所示:
(没有默认值,这个编译正常)
scala> val function_with_default = (x: String) => {x + "!"}
function_with_default: String => java.lang.String = <function1>
(但我无法编译这个...
scala> val function_with_default = (x: String = "default") => {x + "!"}
<console>:1: error: ')' expected but '=' found.
val function_with_default = (x: String = "default") => {x + "!"}
^
知道吗?
没有办法做到这一点。你能得到的最好的是一个同时扩展Function1
和Function0
的对象,其中 的 apply 方法 of Function0
使用默认参数调用另一个 apply 方法。
val functionWithDefault = new Function1[String,String] with Function0[String] {
override def apply = apply("default")
override def apply(x:String) = x + "!"
}
如果你更频繁地需要这样的函数,你可以将默认的 apply 方法分解成一个抽象类DefaultFunction1
如下所示:
val functionWithDefault = new DefaultFunction1[String,String]("default") {
override def apply(x:String) = x + "!"
}
abstract class DefaultFunction1[-A,+B](default:A)
extends Function1[A,B] with Function0[B] {
override def apply = apply(default)
}