0

I am trying to do a match on a value based on its type, and there is a case where the expected type is a generic, like below:

def foo(bar: Matchable) = bar match
    case (bar: Vector[String]) => println(bar.mkString(","))

However, I get the following warning at runtime:

the type test for Vector[String] cannot be checked at runtime

Why cannot it be checked and how could I overcome this?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Weier
  • 1,339
  • 1
  • 10
  • 20
  • 2
    https://stackoverflow.com/questions/16056645/how-to-pattern-match-on-generic-type-in-scala – Dmytro Mitin Dec 13 '22 at 12:13
  • 2
    https://stackoverflow.com/questions/1094173/how-do-i-get-around-type-erasure-on-scala-or-why-cant-i-get-the-type-paramete – Dmytro Mitin Dec 13 '22 at 12:16
  • 1
    I would recommend taking a couple of steps back and reconsider the design that lead to runtime type checking. – Luis Miguel Mejía Suárez Dec 13 '22 at 12:36
  • I have to manipulate entries like `[1,[2,[3,[4,[5,6,7]]]],8,9]` so it's not easy (it's for Advent of Code day 13 FYI) – Weier Dec 13 '22 at 13:00
  • 2
    `sealed trait ListOrValue[A]; case class ListCase[A](list: List[ListOrValue[A]]) extends ListOrValue[A]; case class ValueCase[A](value: A) extends ListOrValue[A]` - a discriminating union which allows recursion would let you preserve type safety. Something which "`Vector[Any]` where `Any` should actually be `Vector[Any]` or `String`" wouldn't allow. There would be also some other options esp in Scala 3 (e.g. sum types + `TypeTest`), but I wouldn't recommend them for an entry level. `sealed`/`enum` would be easier to understand. – Mateusz Kubuszok Dec 13 '22 at 14:27

0 Answers0