繁体   English   中英

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

[英]scala: define default parameters in a function (val) vs using a method (def)

我有以下方法:

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 + "!"}
                                              ^

任何的想法?

没有办法做到这一点。 您可以获得的最好的是一个扩展Function1Function0的对象,其中Function0的apply方法使用default参数调用另一个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)
}

暂无
暂无

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

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