我有一个存储三个绑定(bind)参数的案例类。我想定义可以从任何两个参数构建类的伴随对象,类似于下面的示例,这显然是不正确的:
def test(start : Float = end - duration, duration : Float = end - start, end : Float = start + duration) {
require( abs(start + duration - end) < epsilon )
...
}
val t1 = test(start = 0f, duration = 5f)
val t2 = test(end = 4f, duration = 3f)
val t3 = test(start = 3f, end = 5f)
我可以使用什么技巧来获得类似的使用语法?
最佳答案
您可以使用类型类:
// Represents no argument
object NoArg
// Resolves start, duration, stop
trait DurationRes[A,B,C] {
def resolve(s: A, d: B, e: C): (Float, Float, Float)
}
object DurationRes {
implicit object startEndRes extends DurationRes[Float, NoArg.type, Float] {
def resolve(s: Float, d: NoArg.type, e: Float) = (s, e-s, e)
}
implicit object startDurRes extends DurationRes[Float, Float, NoArg.type] {
def resolve(s: Float, d: Float, e: NoArg.type) = (s, d, s+d)
}
// etc.
}
def test[A,B,C](start: A = NoArg, dur: B = NoArg, end: C = NoArg)
(implicit res: DurationRes[A,B,C]) {
val (s,d,e) = res.resolve(start, dur, end)
// s is start, d duration, e end
}
test(start = 1f, end = 2f)
这样它甚至是类型安全的,你不能调用类似的东西:
test(start = 1f)
甚至
test()
关于scala - 根据scala中的其他参数定义默认命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18197364/