我正在尝试实现这一点:
def buildQuery() {
val restrictions: ConjunctionRestriction[String, Int] =
("name" is "Some One") and ("age" is 20)
}
implicit def stringToEqualsRestrictionBuilder[T](fieldName: String)
: EqualsRestrictionBuilder[T] =
new EqualsRestrictionBuilder[T](fieldName)
implicit def restrictionToConjunctionBuilder[L,R](restriction: Restriction[L])
: ConjunctionBuilder[L,R] =
new ConjunctionBuilder[L,R](restriction)
case class Restrictions(restrictions: Restriction[_]*)
trait Restriction[T] {
def toString: String
}
class EqualsRestriction[T](val fieldName: String, val value: T)
extends Restriction[T] {
override def toString = fieldName + "=" + value
}
class ConjunctionRestriction[A,B](val lhs: Restriction[A],
val rhs: Restriction[B])
extends Restriction[(A,B)] {
override def toString = "(" + lhs + ") AND (" + rhs + ")"
}
class EqualsRestrictionBuilder[T](val fieldName: String,
val restriction: Option[Restriction[T]] = None) {
def is(value: Int) =
new EqualsRestriction[Int](fieldName, value)
def is(value: String) =
new EqualsRestriction[String](fieldName, "\"" + value + "\"")
}
class ConjunctionBuilder[L,R](val lhs: Restriction[L]) {
def and(rhs: Restriction[R]) = new ConjunctionRestriction[L,R](lhs, rhs)
}
编译器给我错误:
error: type mismatch;
found : MyOuterClass.this.EqualsRestriction[Int]
required: MyOuterClass.this.Restriction[R]
val restrictions: ConjunctionRestriction[String, Int] =
("name" is "Some One") and ("age" is 20)
我还没有弄清楚 scala 类型系统。这有什么问题?
谢谢
编辑
通过将 ConjunctionBuilder 更改为只有一种参数类型 L 来修复:
class ConjunctionBuilder[L](val lhs: Restriction[L]) {
def and[R](rhs: Restriction[R]) = new ConjunctionRestriction[L,R](lhs, rhs)
}
implicit def restrictionToConjunctionBuilder[L](restriction: Restriction[L])
: ConjunctionBuilder[L] =
new ConjunctionBuilder[L](restriction)
但是有人可以解释为什么使用 R 参数类型编译失败吗?