用于实现用 Scala 隐式封装的 Java 接口的工厂方法?

发布于 2024-07-12 11:09:51 字数 1008 浏览 4 评论 0原文

我使用 Scala 隐式为 Java 接口定义丰富的包装器:

class RichThing { def richStuff: Unit = {} }

在伴生对象中,我定义了隐式转换和一个 apply 工厂方法:

object RichThing { 
    implicit def rich( thing: JavaThing ) = new RichThing() 
    def apply() = new RichThing()
}

通过这个,我可以实例化该接口的 Java 实现并像使用 RichThing 一样使用它(由于隐式转换):

new JavaThingImpl().richStuff

我还可以使用工厂方法创建一个 RichThing (由于 apply method):

val a = RichThing()

我想做的是以相同的方式实例化该接口的任意 Java 实现。 这是行不通的,因为 Scala 然后会寻找实现的伴生对象,但找不到:

val b = JavaThingImpl() // "not found: value JavaThingImpl"

我可以为 Java 实现创建一个 Scala 伴生对象:

object JavaThingImpl { def apply() = new RichThing() }

但重点是使此方法适用于任何对象(特别是未知)接口的实现。

有什么办法可以实现这一点吗? 例如,要基于 RichThing 对象中的隐式转换为 Java 实现动态创建 Scala 伴随对象?

或者从 Java 端创建 Scala 伴随对象(可能在抽象类中)?

I'm using Scala implicits to define a rich wrapper for a Java interface:

class RichThing { def richStuff: Unit = {} }

In the companion object I define the implicit conversion and an apply factory method:

object RichThing { 
    implicit def rich( thing: JavaThing ) = new RichThing() 
    def apply() = new RichThing()
}

With this, I can instantiate a Java implementation of the interface and use it like a RichThing (due to the implicit conversion):

new JavaThingImpl().richStuff

I can also create a RichThing using the factory method (due to the apply method):

val a = RichThing()

What I'd like to do is instantiate arbitrary Java implementations of the interface in the same way. This doesn't work, as Scala then looks for a companion object of the implementation and can't find one:

val b = JavaThingImpl() // "not found: value JavaThingImpl"

I could create a Scala companion object for the Java implementation:

object JavaThingImpl { def apply() = new RichThing() }

But the point would be to make this work for any (in particular unknown) implementation of the interface.

Is there any way to realize this? For instance, to create Scala companion objects for the Java implementations on the fly, based on the implicit conversion in the RichThing object?

Or to create the Scala companion object from the Java side, maybe in an abstract class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十年九夏 2024-07-19 11:09:51

不,这在 Scala 中是不可能的。 可能可以将其添加到语言中而不影响类型的健全性,但我怀疑额外的复杂性是否值得。

No, this is not possible in Scala. It would probably be possible to add it to the language without compromising type soundness, but I question whether the additional complexity would be worth it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文