简体   繁体   English

具有隐式转换的Scala映射

[英]Scala map with implicit conversion

I have a Scala case class and a corresponding Java class. 我有一个Scala case类和一个对应的Java类。 I've declared an implicit conversion from Scala class to Java class. 我已经声明了从Scala类到Java类的隐式转换。 Now I have a Scala collection of Scala classes, and I want to convert them to Scala collection of Java classes. 现在,我有一个Scala Scala类集合,并且我想将它们转换为Java类的Scala集合。 Is it possible with the implicit conversion? 隐式转换可能吗? Here's what I've tried, naively perhaps: 这是我尝试过的尝试,也许是幼稚的:

case class PositionScala(latitude: Double, longitude: Double)
object PositionScala {
  implicit def toJava(p: PositionScala): Position = new Position(p.latitude, p.longitude) // Position is the Java class
}
...
val p: List[Position] = routeScala.shape.map(p => p) 
                     // routeScala.shape is List[PositionScala]

But it doesn't compile with the type mismatch error. 但是它不会与类型不匹配错误一起编译。 Of course I can call the conversion function explicitly, but it defeats the purpose of using implicit converter. 当然,我可以显式调用转换函数,但是它违背了使用隐式转换器的目的。 Is there a way to do what I want? 有什么方法可以做我想要的吗?

You need to put the type annotation in a different place: routeScala.shape.map(p => p: Position) . 您需要将类型注释放在另一个位置: routeScala.shape.map(p => p: Position) But I'd say this is less clear than just writing routeScala.shape.map(PositionScala.toJava) . 但是我要说的是,这不只是编写routeScala.shape.map(PositionScala.toJava)

您可以通过将转换函数'toJava'传递给map函数来实现:

val p: List[Position] = routeScala.shape.map(toJava)

Additionally to @alexey-romanov 's answer I should make a stand for scala type resolution. 除了@ alexey-romanov的答案外,我还应该支持scala类型解析。

map method for scala collections have pretty complex behaviour. scala集合的map方法具有相当复杂的行为。 It tries to derive resulting collection\\element type basing on visible CanBuildFrom implicit, so it can't say definitely what the result type of map argument should be. 它尝试基于可见的CanBuildFrom隐式派生结果集合\\元素类型,因此它不能明确说明map参数的结果类型应该是什么。 Because of that it can't apply implicit conversion here. 因此,它不能在此处应用隐式转换。

If for example you had 例如,如果您有

val posOpt: Option[PositionScala] = ???

and tried to apply 并尝试申请

val posJava: Option[Position] = posOpt.map(p => p) 

It would found your conversion with no problem. 它会发现您的转换没​​有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM