【问题标题】:Scala's match/case for Option[classOf[...]]Scala 对 Option[classOf[...]] 的匹配/案例
【发布时间】:2014-08-18 02:43:06
【问题描述】:

我需要检查方法返回的类型以调用不同的方法。 这是代码:

class X ...
class Y ...

...

def getType(input:String) : Option[Class[_]] = {
  if ... return Some(classOf[X])
  if ... return Some(classOf[Y])
  ...
}

getType(input) match {
  case Some(classOf[X]) => ... // ERROR
  case Some(classOf[Y]) => ...
  case None => ...
}

但是,我遇到了错误:

可能出了什么问题?

【问题讨论】:

    标签: scala match option


    【解决方案1】:

    我认为你不能在结构匹配中使用classOf。相反,您可以添加一个条件来检查它。

    val opt: Option[Class[_]] = Some(classOf[Int])
    
    opt match {
      case Some(c) if c == classOf[String] => "String"
      case Some(c) if c == classOf[Int] => "Int"
      case None => "No Class"
      case _ => "Some other Class"
    } //yields Int
    

    【讨论】:

      【解决方案2】:

      您可以执行以下操作:

      getType(input) match {
        case Some(x: Class[X]) => ... 
        case Some(y: Class[Y]) => ...
        case None => ...
      }
      

      【讨论】:

      • 这不会受到类型擦除的影响吗?我认为它不起作用。
      • 哈,如果你打错了case Some(Class[Foo]),你会得到unsupported pattern: TypeTree / p3: Class[Foo] @ Class[Foo] (this is a scalac bug.)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 2017-02-25
      • 2018-10-03
      相关资源
      最近更新 更多