解决 Scala 中模糊的隐式转换

编程入门 行业动态 更新时间:2024-10-14 06:16:55
本文介绍了解决 Scala 中模糊的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.util.Collection[A] are possible conversion functions from Iterable[Int] to java.lang.Iterable[Int] Iterable(0,1):java.lang.Iterable[Int] ^

推荐答案

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

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

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

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

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

但是,我认为最好导入 JavaConverters 并使您的转换显式.

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

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

更多推荐

解决 Scala 中模糊的隐式转换

本文发布于:2023-07-14 10:14:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104077.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模糊   隐式   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!