1

Let's say I have something like this:

object IceCream {
  trait IceCream
  case object ChocolateIceCream extends IceCream
  case object VanillaIceCream   extends IceCream
}

whose source code is not mine, and I cannot change. In another program, I would like to reuse this, and make all ice cream flavors be part of another trait. Am I forced to box them, doing something like this?:

object ThingsILike{
  import IceCream._

  trait ThingsILike
  case object  Chocolate                   extends ThingsILike
  case class   IceCreamWrapper(x:IceCream) extends ThingsILike
}

or does the language provide a way to naturally extend them (like Swift does)?

Eduardo
  • 8,362
  • 6
  • 38
  • 72
  • You can use the *extend my library* pattern, or type classes, depending on *what* it is you want to do. – Michael Zajac Jan 23 '16 at 02:17
  • @m-z in the example above, I would like to include `IceCream` objects in the same collection as other `ThingsILike`, and be able to pattern match later on. – Eduardo Jan 23 '16 at 02:27
  • 1
    This may be useful: http://stackoverflow.com/questions/3508077/how-to-define-type-disjunction-union-types – JimN Jan 23 '16 at 03:23
  • @JimN I was experimenting with that a couple of days ago, for another problem, but given the amount of sorcery needed, I would rather box it and pattern match twice. I heard that Dotty does have unboxed union types, so that's something to look forward to. Thank you for the help. – Eduardo Jan 23 '16 at 04:20

1 Answers1

0

You could use implicit to "add" methods to existing classes. You can cause an existing class to be a subclass or pass an isInstanceOf test with a new class or trait. You can however make your own unapply method to make pattern matching do anything you like.

Meir Maor
  • 1,200
  • 8
  • 18