New constructors for classes with Scala rich wrapping (implicit)

时光总嘲笑我的痴心妄想 提交于 2019-12-10 15:32:58

问题


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?


回答1:


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:

class Foo(val bar: Int, val baz: Int) {
  ... class definition ...
}

You could add (in the same file):

object Foo {
  def apply(bar: Int) = new Foo(bar, 0)
}

With this in hand, creating a new Foo instance, just providing the bar parameter, is as easy as

val myBar = 42
val myFoo = Foo(myBar) // Note the lack of the 'new' keyword.

This will result in myFoo being assigned an instance of Foo where bar = 42, and baz = 0.




回答2:


Yes, you need a combination of the "Pimp my Library" approach and an apply factory method.



来源:https://stackoverflow.com/questions/6728886/new-constructors-for-classes-with-scala-rich-wrapping-implicit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!