简体   繁体   English

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

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

I have the following method: 我有以下方法:

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!

I'm trying to achieve the same with a val, but I get a syntax error, like this: 我试图用val实现相同,但我得到一个语法错误,像这样:

(with no default value, this one compiles ok) (没有默认值,这个编译好了)

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

(but I couldn't get this one to compile...) (但我无法将这个编译成......)

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

any idea? 任何的想法?

There is no way to do this. 没有办法做到这一点。 The best you can get is an object that extends both Function1 and Function0 where the apply method of Function0 calls the other apply method with the default parameter. 您可以获得的最好的是一个扩展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 + "!"
}

If you need such functions more often, you can factor out the default apply method into an abstract class DefaultFunction1 like this: 如果你需要更频繁地使用这些函数,你可以将默认的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