0
在一個Scala類中,目標是實現一個Builder模式,並且構造類的參數之一是一個函數,它接收一個元組並且返回一個Double。在Scala中,如何使用元組參數定義一個函數變量
在Builder類中,變量tupleFunc
需要用默認實現來保存此類型的函數。 Builder還會有一個方法tupleFuncIs
覆蓋默認值。
class FunctionProblem private (val tupleFunc: (Boolean, Double, Int) => Double,
val func: Double => Double) {
}
object FunctionProblem {
class Builder {
// problem line follows
private var tupleFunc: ((Boolean, Double, Int) => Double) = (x: (Boolean, Double, Int)) => if (x._1) x._2 else x._3.toDouble
private var func: (Double => Double) = (x: Double) => 0.75 * x
def tupleFuncIs(x: (Boolean, Double, Int) => Double): Builder = { tupleFunc = x; this }
def funcIs(x: Double => Double): Builder = { func = x; this }
def build(): FunctionProblem = new FunctionProblem(tupleFunc, func)
}
def builder(): Builder = new Builder
}
然而,Scala編譯器抱怨類型不匹配的
[ant:scalac] found : ((Boolean, Double, Int)) => Double
[ant:scalac] required: (Boolean, Double, Int) => Double
[ant:scalac] private var tupleFunc: ((Boolean, Double, Int) => Double) = (x: (Boolean, Double, Int)) => if (x._1) x._2 else x._3.toDouble
[ant:scalac] ^
爲什麼有發現,雙括號或更好,但應該如何tupleFunc
被改寫,以滿足編譯器?