Search code examples
scalashapeless

Shapeless TypeCase Wierd Behavior


In the following code snippet:

import shapeless._

val stringList = TypeCase[List[String]]
val intList    = TypeCase[List[Int]]

def patternMatch(a: Any): Unit = a match {
  case stringList(strs) => println("Got Some Strings: " + strs.map(_.size).sum)
  case intList(ints)    => println("Got Some Ints: " + ints.sum)
  case _ =>
}

val ints: List[Int] = Nil

patternMatch(List("hello", "world")) 
patternMatch(List(1, 2, 3))          
patternMatch(ints) // This was printing "Got Some Strings:..."

How is it possible that the last one is matching against Strings? Any reasons?


Solution

  • TypeCase[List[String]] does not match if there is at least one value that is not String. Because Nil - an empty list - has no such values, it matches.


    At runtime, you cannot distinguish between an empty list of strings from an empty list of ints. They are both the same object - Nil, without any type information