目录
Scala error: type mismatch; found : java.util.List[?0] required: java.util.List[B]
问题:
解决:
完整错误:
问题:
import java.util import java.util.stream.Collectors class Animal class Dog extends Animal class Cat extends Animal object ObjectConversions extends App { import java.util.{List => JList} implicit def convertLowerBound[ B <: Animal] (a: JList[Animal]): JList[B] = a.stream().map(a => a.asInstanceOf[B]).collect(Collectors.toList()) val a= new util.ArrayList[Animal]() a.add(new Cat) convertLowerBound[Cat](a) }解决:
当调用Java方法并且仍然想要泛型类型推断时,需要专门传递泛型类型才可以
#亦或者没有导入隐式转换的语句
import scala.collection.JavaConversions._
def convertLowerBound[ B <: Animal] (a: JList[Animal]): JList[B] = a.stream().map[B](a => a.asInstanceOf[B]).collect(Collectors.toList[B]()) #or def convertLowerBound[B <: Animal : TypeTag] (a: JList[Animal]) = a.asInstanceOf[JList[B]]
scala> def convertLowerBound[ B <: Animal] (a: JList[Animal]): JList[B] = a.stream().map[B](a => a.asInstanceOf[B]).collect(Collectors.toList[B]())
convertLowerBound: [B <: Animal](a: java.util.List[Animal])java.util.List[B]
scala> convertLowerBound[Cat](a)
res30: java.util.List[Cat] = [Cat@6325af19, Dog@6ff6743f]
scala> a.add(new Cat())
res16: Boolean = true
scala> convertLowerBound[Cat](a)
res17: java.util.List[Cat] = [Cat@6325af19]
scala> a.add(new Dog())
res19: Boolean = true
scala> convertLowerBound[Cat](a)
res20: java.util.List[Cat] = [Cat@6325af19, Dog@6ff6743f]
found : java.util.List[?0]
required: java.util.List[B]
Note: ?0 >: B, but Java-defined trait List is invariant in type E.
You may wish to investigate a wildcard type such as `_ >: B`. (SLS 3.2.10)
implicit def convertLowerBound[ B <: Animal] (a: JList[Animal]): JList[B] = a.stream().map(a => a.asInstanceOf[B]).collect(Collectors.toList())
参考:Implicit conversion of java.util.List to scala List does not occur
参考:Scala error: type mismatch; found : java.util.List[?0] required: java.util.List[B]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)