在 Scala 2 中,使用 Shapeless,您可以这样做 ( Scastie ):
def f[T <: Product, H <: HList](tupleOfFoos: T)(
implicit gen: Generic.Aux[T, H],
hev: LiftAll[({type E[T] = Foo =:= T})#E, H]
) = tupleOfFoos
LiftAll
确保有Foo =:= X
for each X
in的实例H
,并gen
确保T
andH
不是完全不相关的类型。
在 Dotty 中,您可以为此添加具有匹配类型的证据参数:
type Homogenous[H, T <: Tuple] = T match {
case EmptyTuple => DummyImplicit
case H *: t => Homogenous[H, t]
case _ => Nothing
}
def f[T <: Tuple](tupleOfFoos: T)(using Homogenous[Foo, T]) = tupleOfFoos
这将允许你打电话f((Foo(), Foo(), Foo()))
,但不能f((1, 2, 3))
。
Homogenous
是一个递归匹配类型,其基本情况为EmptyTuple
. 如果一个元组是空的,那么它没有被非 s 填充Foo
,所以类型变为DummyImplicit
,它已经在范围内隐含。否则,我们检查它是否看起来像(H, ...)
/ H *: t
,在这种情况下,我们需要检查元组的其余部分 ( t
) 是否也有效。如果它不匹配第二种情况,我们知道元组是无效的,在这种情况下结果是Nothing
,理智的人不会隐含值。
如果你想使用上下文边界,你可以做一个额外的柯里化类型(Scastie):
type Homo2[H] = [T <: Tuple] =>> Homogenous[H, T]
def f[T <: Tuple : Homo2[Foo]](tupleOfFoos: T) = tupleOfFoos
不幸的是,我无法让它与单一的咖喱类型(Scastie)一起工作:
type Homogenous[H] = [T <: Tuple] =>> T match {
case EmptyTuple => DummyImplicit
case H *: t => Homogenous[H][t]
case _ => Nothing
}