Why 42.asInstanceOf[Int with String] does not throw a ClassCastException?

92 views
Skip to first unread message

Oliver Ruebenacker

unread,
Jan 7, 2016, 3:06:23 PM1/7/16
to scala-user

     Hello,

  Why does this not throw a ClassCast Exception?

scala> 42.asInstanceOf[Int with String]
res0: Int with String = 42

  Note that these do:

scala> 42.asInstanceOf[String]
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
  ... 33 elided

scala> 42.asInstanceOf[String with Int]
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
  ... 33 elided

     Best, Oliver

--
Oliver Ruebenacker
Senior Software Engineer, Diabetes Portal, Broad Institute

som-snytt

unread,
Jan 7, 2016, 3:50:02 PM1/7/16
to scala-user

Try 42.asInstanceOf[Int with String].length to see when the check cast happens.

Similarly, "s".asInstanceOf[String with T] : T for tagging. The compile-time fiction is OK.

Adriaan Moors

unread,
Jan 7, 2016, 6:24:08 PM1/7/16
to som-snytt, scala-user
See "intersection dominator" at http://www.scala-lang.org/files/archive/spec/2.11/03-types.html#type-erasure

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

scala> :power
Power mode enabled. :phase is at typer.
import scala.tools.nsc._, intp.global._, definitions._
Try :help or completions for vals._ and power._

scala> erasure.javaErasure(typeOf[Int with String])
res0: $r.intp.global.erasure.global.Type = Int

scala> erasure.javaErasure(typeOf[String with Int])
res1: $r.intp.global.erasure.global.Type = String

cheers
adriaan


--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Dennis Haupt

unread,
Jan 8, 2016, 1:41:21 AM1/8/16
to Adriaan Moors, som-snytt, scala-user
my guess: in the jvm, you can only declare something as one type as the time
so if you have something that is A and B, but those are separate traits, the scala compiler has to pick one and cast it to the other when needed
 
Gesendet: Freitag, 08. Januar 2016 um 00:23 Uhr
Von: "Adriaan Moors" <adr...@typesafe.com>
An: som-snytt <som....@gmail.com>
Cc: scala-user <scala...@googlegroups.com>
Betreff: Re: [scala-user] Re: Why 42.asInstanceOf[Int with String] does not throw a ClassCastException?
Reply all
Reply to author
Forward
0 new messages