vertti
vertti

Reputation: 7889

New constructors for classes with Scala rich wrapping (implicit)

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?

Upvotes: 4

Views: 1232

Answers (2)

Alex Dean
Alex Dean

Reputation: 16075

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

Upvotes: 0

Shadowlands
Shadowlands

Reputation: 15074

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.

Upvotes: 2

Related Questions