Scala error: type mismatch; found : java.util.List[?0] required: java.util.List[B]
Posted Data+Science+Insight
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Scala error: type mismatch; found : java.util.List[?0] required: java.util.List[B]相关的知识,希望对你有一定的参考价值。
Scala error: type mismatch; found : java.util.List[?0] required: java.util.List[B]
目录
Scala error: type mismatch; found : java.util.List[?0] required: java.util.List[B]
问题:
由于Scala类型推断和Java类型推断不兼容;
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]
完整错误:
<console>:15: error: type mismatch;
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]
以上是关于Scala error: type mismatch; found : java.util.List[?0] required: java.util.List[B]的主要内容,如果未能解决你的问题,请参考以下文章
局域网或者云服务器搭建jupyter notebook浏览器(chrome)打开ERR_SSL_VERSION_OR_CIPHER_MISMATCH
Jhipster 上的 ERR_SSL_VERSION_OR_CIPHER_MISMATCH
为 Tomcat 7 配置 SSL 会导致 ERR_SSL_VERSION_OR_CIPHER_MISMATCH 错误