1

I am trying to create a method that will take a list of Objects and a list of Types and then check whether a particular object matches a particular type.

I tried to create a dummy example. In the following code validate method takes list of objects and a List of type then tried to validate the types of each object. I know following code is wrong but I just created to communicate the problem, it would be really great if you can tell me how can I do this in Scala.

object T extends App {
  trait MyT
  case class A(a: Int) extends MyT
  case class B(b: Int) extends MyT

  def validate(values: Seq[Any], types: Seq[MyT]): Seq[Boolean] =
    for ((v, ty: MyT) ← values.zip(types)) yield v.isInstanceOf[ty]

  // create objects
  val a = A(1)
  val b = B(1)

  // call validate method 
  validate(Seq(a, b), Seq(A, B))

}

3
  • 1
    Types are not objects. They cannot be stored in containers. But you can use Class or TypeTags. Commented Jan 20, 2022 at 6:16
  • Does it need to work with generic types? Otherwise just go with Class. Commented Jan 20, 2022 at 6:52
  • @GaëlJ All Types I would like to pass in the second argument of validate method are going be sub type of a trait. Commented Jan 20, 2022 at 7:50

1 Answer 1

3

Types are not values, so you can't have a list of them.
But, you may use Class instead:

def validate(values: Seq[Any], types: Seq[Class[_ <: MyT]]): Seq[Boolean] =
  values.lazyZip(types).map {
    case (v, c) =>
      c.isInstance(v)
  }

Which can be used like this:

validate(Seq(a, b), Seq(classOf[A], classOf[B]))
// res: Seq[Boolean] = List(true, true)

You can see the code running here.

However, note that this will break if your classes start to have type parameters due to type erasure.


Note, I personally don't recommend this code since, IMHO, the very definition of validate is a code smell and I would bet you have a design error that lead to this situation.

I recommend searching for a way to avoid this situation and solve the root problem.

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

Comments

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.