与泛型的模式匹配 [英] Pattern matching with generics

查看:46
本文介绍了与泛型的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下类模式匹配:

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

是否可以根据模式匹配得出的内容以通用方式引用 MyClass?例如,如果我有多个 MyClass 的子类,我是否可以编写一个简单的模式匹配将匹配的类型传递给 someMethod:

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]
}

推荐答案

不幸的是,类型在 Scala 中并不是真正的一等公民.例如,这意味着您不能对类型进行模式匹配.由于继承自 Java 平台的愚蠢类型擦除,大量信息丢失.

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.

我能想到的最好的就是

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

所以如果你想挽救自己严重的脑损伤,我会忘记这个项目或寻找另一种语言.也许 Haskell 在这里更好?我仍然希望我们最终可以匹配类型,但我的希望非常低.

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.

也许 scalaz 的人想出了一个解决方案,他们几乎将 Scala 的类型系统利用到了极限.

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

这篇关于与泛型的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆