[英]Scala composition of generic types
I have a complex use case of generics type which has been simplified below 我有一个泛型类型的复杂用例,下面已对其进行了简化
trait A
class AB extends A{
val v = 10
}
trait X[T<:A]{
def request: T
}
class XY extends X[AB]{
def request = new AB()
}
class Test extends App{
/**
* X[A]
* X[AB]
* XY[A]
* XY[AB]
*/
def test[C<:A, D <: X[C]](t:Int)(input: D): Unit ={
print(input.getClass.getName)
}
implicit val req = new XY()
test(2)(req)
}
test method should support the Type scenarios defined in comment section. 测试方法应支持注释部分中定义的类型方案。 I'm getting the below compilation error. 我收到以下编译错误。
Error:(33, 7) inferred type arguments [XY] do not conform to method test's type parameter bounds [D <: X[Nothing]] test(2)(req)
Is this syntactically legal? 这在语法上合法吗? Thanks in advance. 提前致谢。
Nothing
in compile error usually means that some type wasn't inferred. 编译错误Nothing
通常意味着未推断出某种类型。
Try to specify type parameters explicitly 尝试明确指定类型参数
test[AB, XY](2)(req)
Generic nested type inference works with arity-2 but not with currying 通用嵌套类型推断适用于arity-2,但不适用于curring
The compiler can't infer the type of C
in 2 steps with a definition like this. 编译器无法通过这样的定义分两步推断C
的类型。
So either have the compiler do it in 1 step, by having both D
and C
in the definition of the input
argument: 因此,要么让编译器一步一步完成,要么在input
参数的定义中同时包含D
和C
:
def test[C <: A, D <: X[C]](t: Int)(input: D with X[C]): Unit
Or have an implicit evidence for D <: X[C]
, that will help the compiler to infer C
in 2 steps: 或者有D <: X[C]
的隐式证据,这将有助于编译器分两步推断C
:
def test[C <: A, D <: X[_]](t: Int)(input: D)(implicit ev: D <:< X[C]): Unit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.