代码之家  ›  专栏  ›  技术社区  ›  prosseek

Scala对选项[classOf[…]]的匹配/大小写

  •  1
  • prosseek  · 技术社区  · 10 年前

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

    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 => ...
    }
    

    然而,我遇到了错误:

    enter image description here

    可能出了什么问题?

    2 回复  |  直到 2 年前
        1
  •  5
  •   Kigyo    10 年前

    我想你不能用 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
  •  0
  •   David    10 年前

    您可以执行以下操作:

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