Kiolimandars
Kiolimandars

Reputation: 55

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 (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)

Upvotes: 2

Views: 191

Answers (1)

Alin Gabriel Arhip
Alin Gabriel Arhip

Reputation: 2638

I don't recommend using parameters of type Any or pattern matching for every type like this, but putting that aside, for your particular use case - 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'
    // etc.
    case _ => // treat default case
}

Upvotes: 2

Related Questions