解决Scala中模糊的隐式转换

Yan*_*ang 7 scala

有什么方法可以选择在下面使用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]
               ^
Run Code Online (Sandbox Code Playgroud)

Aar*_*rup 12

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

import scala.collection.JavaConversions.{asJavaCollection=>_,_}
Run Code Online (Sandbox Code Playgroud)

这说,"导入JavaConversions的所有成员,除了asJavaCollection".

但是,我认为最好导入JavaConverters并明确转换.

import scala.collection.JavaConverters._

Iterable(0,1).asJava
Run Code Online (Sandbox Code Playgroud)