我有下面的構造在Scala中可以編寫放置在函數參數中的表達式,默認參數值嗎?
class Indexer(
index: String,
host: String,
port: Int = DEFAULT_ES_PORT)
我只是想通過端口參數,如果它不是-1,否則我要使用默認值。 我天真的做法是:
val esi = new Indexer(
index = es.index,
host = es.getHost,
port = if (es.getPort != -1) es.getPort
)
,但4號線我得到理所當然的編譯器錯誤:
type mismatch; found : Unit required: Int Error occurred in an application involving default arguments.
因爲else分支的計算結果爲單位。 我當然可以寫這樣的:
val esi = if (es.getPort != -1) {
new Indexer(
index = es.index,
host = es.getHost,
port = es.getPort
)
} else {
new Indexer(
index = es.index,
host = es.getHost
)
}
但我不知道是否有一個更簡潔的方式?
尼斯方法,並使用這種方法,你甚至都不需要給默認值的端口類索引。 – curious 2015-04-02 12:08:43