strange generic types matching

31 views
Skip to first unread message

Georgii Dernovyi

unread,
Jul 9, 2016, 4:37:21 PM7/9/16
to scala-user
I found subj for me (sc 2.11.8)

val s = Seq(Some(1))

s match{
case h: List[String] => h(0)
case _ => 8
}
output:
s: Seq[Some[Int]] = List(Some(1))

res0: Any = Some(1) //???? 


Another weirdness

val s = Seq(Some(1))

s match{
case h: List[Int] => h(0)
case _ => 8
}
output:
s: Seq[Some[Int]] = List(Some(1))

java.lang.ClassCastException: scala.Some cannot be cast to java.lang.Integer
	at scala.runtime.BoxesRunTime.unboxToInt(test.sc:97)
	at #worksheet#.#worksheet#(test.sc:4)

Is the compiler able to match generic types?


Serge

unread,
Jul 9, 2016, 4:52:58 PM7/9/16
to scala...@googlegroups.com
>Is the compiler able to match generic types?
No.

See warning:

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_91).
Type in expressions for evaluation. Or try :help.

scala> val s = Seq(Some(1))
s: Seq[Some[Int]] = List(Some(1))

scala> s match{
| case h: List[String] => h(0)
| case _ => 8
| }
<console>:14: warning: non-variable type argument String in type pattern List[String] (the underlying of List[String]) is unchecked since it is eliminated by erasure
case h: List[String] => h(0)
^
res0: Any = Some(1)


Georgii Dernovyi

unread,
Jul 10, 2016, 1:06:38 AM7/10/16
to scala-user
Thanks! Is it only for me obvious that it is a big compiler lack? :) I have to redesign my program, write a lot junk code just because Scala follows the questionable standpoint far from obvious logic ? Hmm 

Oleksandr Olgashko

unread,
Jul 10, 2016, 3:06:18 AM7/10/16
to Georgii Dernovyi, scala-user
Type erasure is more jvm (rather than scala) issue. For jvm, List[Foo] == List[Bar] == List[String] == List[Object] at runtime.

You can try typetags / classtags, they might be useful.
Reply all
Reply to author
Forward
0 new messages