【问题标题】:Resolving ambiguous implicit conversions in Scala解决 Scala 中不明确的隐式转换
【发布时间】:2011-08-05 08:33:40
【问题描述】:

在下面有什么方法可以选择使用 asJavaIterable 吗?我知道我可以拼出那个特定的函数名,但我想知道我是否可以明确地指定我想要的类型。我也很好奇为什么 asJavaIterable 没有优先于 asJavaCollection。

scala> import scala.collection.JavaConversions._
import scala.collection.JavaConversions._

scala> Iterable(0,1):java.lang.Iterable[Int]
<console>:11: error: type mismatch;
 found   : Iterable[Int]
 required: java.lang.Iterable[Int]
Note that implicit conversions are not applicable because they are ambiguous:
 both method asJavaIterable in object JavaConversions of type [A](i: Iterable[A])java.lang.Iterable[A]
 and method asJavaCollection in object JavaConversions of type [A](i: Iterable[A])java.util.Collection[A]
 are possible conversion functions from Iterable[Int] to java.lang.Iterable[Int]
       Iterable(0,1):java.lang.Iterable[Int]
               ^

【问题讨论】:

    标签: scala


    【解决方案1】:

    可以限制导入的范围,以便不考虑 asJavaCollection

    import scala.collection.JavaConversions.{asJavaCollection=>_,_}
    

    这表示,“导入 JavaConversions 的所有成员,除了 asJavaCollection”。

    但是,我认为最好导入 JavaConverters 并明确您的转化。

    import scala.collection.JavaConverters._
    
    Iterable(0,1).asJava
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      相关资源
      最近更新 更多