【问题标题】:Case Switch Statement with Class Object in ScalaScala中带有类对象的Case Switch语句
【发布时间】:2019-07-09 23:57:20
【问题描述】:

我正在尝试在 Scala 中使用 case switch 语句来检查 Java Class 对象代表的类/类型。我不能传递实际的对象,但我可以获得类,我需要根据该类对象执行不同的逻辑。例如,

def foo(classObj: Class[_]): Any = {
  classObj match {
    case map: Map[String, String] => doMapThings()
    case str: String => doStringThings()
  }
}

但是,这并没有真正起作用,因为 case 语句正在查看 Class 的类型,即 Class,并且永远不会是 Map 或 String。如何获取 classObj 代表的类型/类并与之匹配?

【问题讨论】:

  • 你能解释一下这件事的背景吗?传递一个类对象并返回Any 感觉就像是在对抗类型系统而不是使用它。为什么不能传递对象?

标签: scala reflection pattern-matching type-erasure


【解决方案1】:

为什么不简单地做显而易见的事情:

def foo(c: Class[_]): Unit = {
  if (c == classOf[Map[_, _]]) println("do Map things") 
  else if (c == classOf[String]) println("do string things") 
  else println("do sth. else") }
}

您可以使用if-guards 将其重写为match-表达式:

c match {
  case x if x == classOf[Map[_, _]] => ... 
  ...
}

但这似乎并没有更短或更清晰。另请注意:由于类型擦除,您无法在运行时区分 Map[Int, Double]Map[String, String]

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 2013-09-24
    • 2022-06-22
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2016-01-18
    相关资源
    最近更新 更多