1

I want to use isInstanceOf to decide the type of a variable, however isInstanceOf[T] requires T and T has to be a class decided in compile time. I hope I can make it a variable.

See the example code:

class A{ ... }
class B{ ... }

val class_map = Map( classOf[A] -> 1, classOf[B] -> 2 )
val a = new A()
class_map.keys foreach { i =>
   if (a.isInstanceOf[ i ])  // how to make this statement work?
     println(class_map[i])
}
1
  • 3
    isInstanceOf is usually a code smell, and this looks like an XY Problem, can you describe the broader problem you want yo solve. There may be better alternatives. Commented Sep 28, 2019 at 16:53

2 Answers 2

2

You can use isInstance method of the Class object:

val matchingValues = class_map.collect {
  case (clazz, value) if clazz.isInstance(a) => value
}

matchingValues foreach println
Sign up to request clarification or add additional context in comments.

Comments

0

If I were you, I'd take a different approach, along the lines of:

sealed trait Arg
case class A{ ... } extends Arg
case class B{ ... } extends Arg

val class_map: Arg => Int = {
  case A => 1
  case B => 2
}

val a = new A()
println(class_map(a)) // will print 1

3 Comments

I don't think you can write case A => 1, if A is a class.
@worldterminator On the contrary, that's what pattern matching is for. But also, why don't you try it yourself?
@worldterminator apologies, I didn't realise those were not case classes :facepalm: . Once you make them so, it compiles and works (slightly adjusting the match block's syntax).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.