scala:定义函数(val)中的默认参数vs使用方法(def)

ope*_*sas 10 functional-programming scala

我有以下方法:

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!
Run Code Online (Sandbox Code Playgroud)

我试图用val实现相同,但我得到一个语法错误,像这样:

(没有默认值,这个编译好了)

scala> val function_with_default = (x: String) => {x + "!"}
function_with_default: String => java.lang.String = <function1>
Run Code Online (Sandbox Code Playgroud)

(但我无法将这个编译成......)

scala> val function_with_default = (x: String = "default") => {x + "!"}
<console>:1: error: ')' expected but '=' found.
       val function_with_default = (x: String = "default") => {x + "!"}
                                              ^
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Kim*_*bel 5

没有办法做到这一点.你可以得到的最好的是扩展双方的对象Function1,并Function0在那里的申请方法Function0调用其他应用方法具有默认参数.

val functionWithDefault = new Function1[String,String] with Function0[String] {
  override def apply = apply("default")
  override def apply(x:String) = x + "!"
}
Run Code Online (Sandbox Code Playgroud)

如果您更频繁地需要这些函数,可以将默认的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)
}
Run Code Online (Sandbox Code Playgroud)