简体   繁体   中英

Get The Type of an Input Variable Declared as "Any" in Scala

I am trying to handle any type of input in my function arguments. For my application, I just need the first letter of the type to treat each scenario (ie: s-> String, i-> Integer...).

This code works fine for Int and String but not for the other types:

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'}

For double, and booleans, it gives this error:

Exception in thread "main" scala.MatchError: class java.lang.Double (of class java.lang.String)

You can use the type directly in the pattern match:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM