Scala与Option [classOf [...]]的匹配/大小写

pro*_*eek 1 scala match option

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

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 => ...
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到了错误:

在此输入图像描述

可能有什么问题?

Kig*_*gyo 5

我认为你不能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
Run Code Online (Sandbox Code Playgroud)