【问题标题】:Get The Type of an Input Variable Declared as "Any" in Scala获取在 Scala 中声明为 \"Any\" 的输入变量的类型
【发布时间】:2022-08-16 10:05:20
【问题描述】:

我正在尝试处理函数参数中的任何类型的输入。对于我的应用程序,我只需要类型的第一个字母来处理每个场景(即:s-> String、i-> Integer...)。

此代码适用于 Int 和 String 但不适用于其他类型:

def getTypeChar(Value: Any): Char = Value.getClass.toString match {
case \"class java.lang.Integer\" => \'i\'
case \"class java.lang.String\" => \'s\'
case \"double\" => \'f\'
case \"boolean\" => \'b\'
case \"class scala.collection.immutable.$colon$colon\" => \'c\'}

对于双精度和布尔值,它会给出以下错误:

线程 \"main\" scala.MatchError 中的异常:类 java.lang.Double(属于类 java.lang.String)

  • 为什么不使用case \"class java.lang.Double\" => 而不是case double =>
  • 先不管为什么输入是Any 的问题——你为什么不使用普通的模式匹配(Value match { case _ : Int => \'i\'; ... })?
  • @k314159 当我测试 getClass 的双重打印时,这就是它给出的。
  • @MateuszKubuszok 我对此一无所知。但是谢谢你指出

标签: java scala types any


【解决方案1】:

我不建议使用 Any 类型的参数或像这样的每种类型的模式匹配,但对于您的特定用例 - 您可以直接在模式匹配中使用该类型:

def getTypeChar(value: Any): Char = value match {
    case _: Integer => 'i'
    case _: String  => 's'
    case _: Double  => 'f'
    case _: Boolean => 'b'
    case _ :: _     => 'c'
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2021-03-21
    相关资源
    最近更新 更多