4

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?

vertti
  • 7,539
  • 4
  • 51
  • 81

2 Answers2

2

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.

Shadowlands
  • 14,994
  • 4
  • 45
  • 43
  • Yes. @Janne, in short, you're right, you simply can't “emulate” a new constructor that you'd call with `new`, but you can use this technique instead. – Jean-Philippe Pellet Jul 18 '11 at 07:25
  • The library is a third party library so I don't want to modify the classes there and I think for the same reason I can't create companion objects for those classes? – vertti Jul 18 '11 at 07:34
0

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

Alex Dean
  • 15,575
  • 13
  • 63
  • 74