[英]Constrain a class with implicit evidence
Say I have this: 说我有这个:
trait Animal {
type Species
}
I can easily enough write a function that only takes two animals of the same species 我可以很容易地编写一个只需要同一物种的两只动物的功能
def breed(a: Animal, b: Animal)(implicit evidence: a.Species =:= b.Species) = ???
but I want to create a class with the same sort of constraint: 但我想创建一个具有相同类型约束的类:
class Bed(a: Animal, b: Animal)(implicit evidence: a.Species =:= b.Species)
but it won't compile. 但它不会编译。 I've tried a few combinations of trying to use traits with stable identifiers and constraints and what not, but no matter what I do -- I seem to always end up with problems 我尝试了一些尝试使用具有稳定标识符和约束的特征的组合,但不管怎么样,但无论我做什么 - 我似乎总是遇到问题
trait Bed {
type T
def a: Animal { type Species = T }
def b: Animal { type Species = T }
}
object Bed {
def apply(a1: Animal, b1: Animal)(implicit ev: a1.Species =:= b1.Species) = new Bed {
type T = b1.Species
def a = a1 // this line won't compile, as the compiler can't see the two species are equal ?
def b = b1
}
}
Thanks. 谢谢。
You can express the constraint via a type argument on Bed.apply instead of via a type equality constraint, 您可以通过Bed.apply上的类型参数表示约束,而不是通过类型相等约束,
object Bed {
def apply[T1](
a1: Animal { type Species = T1 },
b1: Animal { type Species = T1 }) = new Bed {
type T = T1
def a = a1
def b = b1
}
}
This can be made a little terser with the aid of a type alias, 借助类型别名可以做到这一点,
type AnimalAux[S] = Animal { type Species = S }
object Bed {
def apply[T1](a1: AnimalAux[T1], b1: AnimalAux[T1]) =
new Bed {
type T = T1
def a = a1
def b = b1
}
}
Sample REPL session, 示例REPL会话,
scala> trait Dog
defined trait Dog
scala> val tigger = new Animal { type Species = Dog }
tigger: Animal{type Species = Dog} = $anon$1@64bd8f9c
scala> val zebedee = new Animal { type Species = Dog }
zebedee: Animal{type Species = Dog} = $anon$1@61f2bf35
scala> Bed(tigger, zebedee)
res0: Bed{type T = Dog} = Bed$$anon$1@2b0ce330
scala> val b = Bed(tigger, zebedee)
b: Bed{type T = Dog} = Bed$$anon$1@681c81de
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.