gpt4 book ai didi

java - 如何在 Scala 中向现有 Java 类添加工厂方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:20:56 25 4
gpt4 key购买 nike

在纯 Scala 环境中,如果我想向现有对象“添加”工厂方法,我可以执行以下操作:

object Test

object Extensions {

object RichTest {
def someFactory = new Test()
}
implicit def fromTest(t: Test.type) = RichTest

}

...

import Extensions._
val t = Test.someFactory

我需要将这样的功能与现有的 Java 类结合使用。在我的具体示例中,我想向类 com.google.android.maps.GeoPoint 添加工厂方法 fromLocation(我想每个 Android 开发人员都知道为什么这会很有用 ;-))。

但是,如果我尝试做类似的事情

implicit def fromGeoPoint(t: GeoPoint.type) = RichTest

我收到一个错误说明

type mismatch; found : com.google.android.maps.GeoPoint.type (with underlying type object com.google.android.maps.GeoPoint) required: AnyRef

所以我想知道是否有任何方法可以实现上述方法 - 或者提供从 LocationGeoPoint 的隐式转换是 Scala 中的首选方式所以需要 GeoPoint 时可以使用 Location 吗?


根据评论要求,一个使用场景:

// Callback you get from the GPS
override def onLocationChanged(l: Location) {
// You want to put a marker on a map, hence a GeoPoint is required
val gp: GeoPoint = GeoPoint.fromLocation(location)
val item = new OverlayItem(gp, ...)
....
}

但是,请记住,这只是一般问题的一个具体示例;-)

最佳答案

从 Scala 版本 2.9.1 开始,无法使用工厂方法扩展 Java 类。

但是,有三种替代解决方案:

  1. Scala compiler plugin以适应所需的更改,然后扩展 Java 类。
  2. 创建一个独立的工厂方法。
  3. 完全避免使用工厂方法并添加隐式转换,以便始终可以使用 Location 对象代替 GeoPoint。

如果我经常使用 Location -> GeoPoint 或任何其他转换,我个人会选择第三个选项,尤其是在转换可以的情况下始终无一异常(exception)地完成并且类接口(interface)不重叠。

implicit def geoPointFromLocation(l: Location):GeoPoint = new GeoPoint...

override def onLocationChanged(l: Location) {
val gp: GeoPoint = l // let Scala compiler do the conversion for you
val item = new OverlayItem(gp, ...)
....
// or just pass the location to OverlayItem constructor directly
val item2 = new OverlayItem(l, ...)
}

关于java - 如何在 Scala 中向现有 Java 类添加工厂方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9546973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com