在纯 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 类相结合。在我的具体示例中,我想在类中添加一个工厂方法fromLocation
(com.google.android.maps.GeoPoint
我想每个 Android 开发人员都会知道为什么这会有用 ;-))。
但是,如果我尝试做类似的事情
implicit def fromGeoPoint(t: GeoPoint.type) = RichTest
我收到一条错误消息
类型不匹配; 找到:com.google.android.maps.GeoPoint.type(带有底层类型对象 com.google.android.maps.GeoPoint) 需要:AnyRef
所以我想知道是否有任何方法可以实现上述方法 - 或者提供隐式转换 from Location
toGeoPoint
是 Scala 中的首选方式,以便在Location
需要时可以使用 a GeoPoint
?
根据评论中的要求,使用场景:
// 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, ...)
....
}
但是,请记住,这只是一般问题的一个具体示例;-)