scala - 根据scala中的其他参数定义默认命名参数

标签 scala named-parameters

我有一个存储三个绑定(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/

相关文章:

scala - 带有 scala 宏的非 scala 源位置

javascript - pg-promise,使用带有嵌套对象的命名参数

dart - 为了清楚起见,我想在 Dart 中使用命名参数。我应该如何处理它们?

scala - 拒绝理解

Scala:isInstanceOf 后跟 asInstanceOf

java - Scala + Eclipse + Casbah = 对象 mongodb 不是包 com 的成员

scala - 可选参数值是否可能依赖于Scala中的另一个参数

scala - Scala 如何知道调用什么方法(命名参数)

sql - ‘?’在SQL中代表什么?

scala - Scala 中的内部类与不变性