Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching with generics

Tags:

scala

Given the following class pattern match:

clazz match {
  case MyClass => someMethod[MyClass]
}

Is it possible to refer to MyClass in a generic way based on what the pattern match came up with? For example, if I have multiple subclasses of MyClass, can I write a simple pattern match to pass the matched type to someMethod:

clazz match {
  case m <: MyClass => someMethod[m]
}
like image 522
earldouglas Avatar asked Aug 14 '26 18:08

earldouglas


1 Answers

Unfortunately types are not really first class citizens in Scala. This means for example that you cannot do pattern matching on types. A lot of information is lost due to stupid type erasure inherited from the Java platform.

I don't know if there are any improvement requests for this, but this is one of the worst problems in my option, so someone should really come up with such a request.

The truth is you will need to pass around evidence parameters, at best in the form of implicit parameters.

The best I can think of goes in the line of

class PayLoad

trait LowPriMaybeCarry {
   implicit def no[C] = new NoCarry[C]
}
object MaybeCarry extends LowPriMaybeCarry {
   implicit def canCarry[C <: PayLoad](c: C) = new Carry[C]
}

sealed trait MaybeCarry[C]
final class NoCarry[C] extends MaybeCarry[C]
final class Carry[C <: PayLoad] extends MaybeCarry[C] {
   type C <: PayLoad
}

class SomeClass[C <: PayLoad]

def test[C]( implicit mc: MaybeCarry[C]) : Option[SomeClass[_]] = mc match {
   case c: Carry[_] => Some(new SomeClass[ c.C ])
   case _ => None
}

but still I can't get the implicits to work:

test[String]
test[PayLoad]  // ouch, not doin it
test[PayLoad](new Carry[PayLoad])  // sucks

So if you want to save yourself serous brain damage, I would forget about the project or look for another language. Maybe Haskell is better here? I'm still hoping that we can eventually match types, but my hopes are pretty low.

Maybe the guys from scalaz have come up with a solution, they pretty much exploited the type system of Scala to the limits.

like image 194
0__ Avatar answered Aug 20 '26 04:08

0__