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],第1张

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]

完整错误:

     :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]

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5438483.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存