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 (i.e: 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)
CodePudding user response:
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'
}