簡體   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