开发者

Resolving ambiguous implicit conversions in Scala

开发者 https://www.devze.com 2023-03-25 04:05 出处:网络
Any way to opt to use asJavaIterable in the following? I know I can just spell out that particular function name, but I\'m wondering if I can just declaritively specify the type I want. I\'m also curi

Any way to opt to use asJavaIterable in the following? I know I can just spell out that particular function name, but I'm wondering if I can just declaritively specify the type I want. I'm also curious why asJavaIterable isn't taking precedence over 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.ut开发者_开发百科il.Collection[A]
 are possible conversion functions from Iterable[Int] to java.lang.Iterable[Int]
       Iterable(0,1):java.lang.Iterable[Int]
               ^


It's possible to limit the scope of the import so that asJavaCollection will not be considered:

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

This says, "import all members of JavaConversions, except asJavaCollection".

However, I think its preferable to import JavaConverters and make your conversions explicit.

import scala.collection.JavaConverters._

Iterable(0,1).asJava
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号