具有 Scala 丰富包装(隐式)的类的新构造函数
在 Scala 中,您可以通过创建包装类并使用“隐式定义”将原始类转换为丰富的包装类,向现有类“添加新方法”。
我有一个用于图形的java库,它使用大量带有长浮点数列表的构造函数。我很想通过丰富的包装向这些类添加新的构造函数,但这似乎不像上面的方法那样工作。换句话说,我希望有更简单的构造函数,但仍然能够继续使用原始类名而不是某些包装类名,但目前我没有看到其他选项。
有想法吗?
In Scala, you can "add new methods" to existing classes by creating wrapper class and using "implicit def" to convert from the original class to the rich wrapper class.
I have a java library for graphics that uses plenty of constructors with looong lists of floats. I would love to add new constructors to these classes with rich wrapping but this doens't seem to work like the above for methods. In other words, I would like to have simpler constructors but still to be able to keep using the original class names and not some wrapper class names but currently I see no other options.
Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您想使用 Scala 的 apply(...) 工厂方法,您可以将其构建到类的伴随对象中。
例如,如果您有:
您可以添加(在同一个文件中):
有了这个,创建一个新的 Foo 实例,只需提供 bar 参数,就像这样简单
这将导致 myFoo 被分配一个 Foo 实例,其中条 = 42,巴兹 = 0。
Sounds like you want to use Scala's apply(...) factory methods, which you build in to the companion object for your class.
For example, if you have:
You could add (in the same file):
With this in hand, creating a new Foo instance, just providing the bar parameter, is as easy as
This will result in myFoo being assigned an instance of Foo where bar = 42, and baz = 0.
是的,您需要结合使用“Pimp my Library”方法和应用工厂方法。
Yes, you need a combination of the "Pimp my Library" approach and an apply factory method.