简体   繁体   English

Scala - 通用类型不进行类型检查

[英]Scala - Generic type does not type check

I am trying to understand my mistake in implementing generics.我试图理解我在实现泛型时的错误。 I have a trait which defines a method that returns a reference with an upper type bound of the trait.我有一个 trait,它定义了一个方法,该方法返回一个带有该 trait 类型上限的引用。 How ever a var reference to an implementation of the trait fails to type check with Expression of type Capability[Class] doesn't conform to expected type Capability[Trait]对特性实现的 var 引用如何无法使用类型Expression of type Capability[Class] doesn't conform to expected type Capability[Trait]进行类型检查Expression of type Capability[Class] doesn't conform to expected type Capability[Trait]

Here is the code:这是代码:

trait IAITask {
  def taskTypeReference[T >: IAITask]: Capability[T]
}

object Tasks {
   var Walk: Capability[Walk] = _
}

class Walk extends IAITask {
  override def taskTypeReference[T >: IAITask]: Capability[IAITask] = Tasks.Walk //This line does not type check
}

If it's a Java interface, then you might want to try to imitate Java's use-site variance by wildcards:如果它是 Java 接口,那么您可能想尝试通过通配符模仿 Java 的使用站点差异:

trait Capability[A]

trait IAITask {
  def taskTypeReference: Capability[_ <: IAITask]
}

object Tasks {
   var Walk: Capability[Walk] = _
}

class Walk extends IAITask {
  override def taskTypeReference: Capability[_ <: IAITask] = Tasks.Walk
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM