vaibhavbarmy
vaibhavbarmy

Reputation: 339

Conditions based on type of a variable in scala

I want to handle my if condition based on the type of a variable which is predefined to be Any type and later it got updated to a type either String, Int, double, List or Map

if (type(x)==int){.....}
else if (type(x)==Map){....}

and so on

Is there a function to get the type of a variable or how can i get the type of a variable to use it in if conditions.I know one of the way is to use

x.getClass.getSimpleName

but when the type of x is a Map it prints Map1 or Map2 for different Maps which i am not sure what 1 and 2 denotes here so i cant use it in the if condition since

if (x.getClass.getSimpleName==Map){....}

will be false as I dont know Map1 or Map2 will come

Upvotes: 3

Views: 1740

Answers (1)

om-nom-nom
om-nom-nom

Reputation: 62835

We call this pattern matching and it's one of the most awesome scala parts:

def foo(x: Any) = x match {
  case m: Map[_,_] => println("I'm a map!")
  case d: Double   => println("I'm a double")
  case i: Int      => println("I'm an int")
  case xs: List[_] => println("I'm a list")
}

Underscores denote any type, i don't care which one

Upvotes: 10

Related Questions