Generics match patterns

Given the following class pattern matching:

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

Is it possible to refer to MyClass in general terms based on what the template encountered? For example, if I have several subclasses of MyClass, can I write a simple pattern match to pass the mapped type to someMethod :

 clazz match { case m <: MyClass => someMethod[m] } 
+3
source share
2 answers

Unfortunately, types are not first class citizens in Scala. This means, for example, that you cannot match patterns by type. A lot of information is lost due to a silly erasure of a type inherited from the Java platform.

I do not know if there are any improvements for this, but this is one of the worst problems in my version, so someone should really come up with such a request.

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

The best I can think of is on the line

 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[ cC ]) case _ => None } 

but still i can't get implicits to work:

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

So, if you want to keep serous brain damage, I would forget about the project or look for another language. Is Haskell better here? I still hope that we can eventually match the types, but my hopes are pretty low.

Perhaps the guys from scalaz came up with a solution, they pretty much used the Scala type system to the limits.

+7
source

Your code is not entirely clear, because at least in java clazz this is a typical name for variables like java.lang.Class and variants. I still think that clazz not an instance of Class , but of your own class.

In Java and Scala, given the o: AnyRef object, you can access its class at runtime via o.getClass: Class[_] and, for example, instantiate this class through the Reflection API. However, type parameters are passed at compile time, so you cannot pass an as-is type at compile time. Either you use AnyRef all over the place as a type (which will work, I suppose), or you use the reflection API if you have more complex needs.

0
source

Source: https://habr.com/ru/post/1390157/


All Articles