Advertisement
Guest User

Why does ClassCastException not happen in method?

a guest
Mar 13th, 2014
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.70 KB | None | 0 0
  1. object Test {
  2.   trait MyType
  3.   trait Ext extends MyType
  4.  
  5.   case class Non() extends MyType
  6.  
  7.   def caster[A <: MyType](a: MyType) = {
  8.     a.asInstanceOf[A] // Exception should happen here, but doesn't
  9.     println("This should never print")
  10.   }
  11.  
  12.   def run() {
  13.     val b = caster[Ext](Non())
  14.     println("No exception yet.")
  15.     val c = Non().asInstanceOf[Ext] // Exception is thrown if we do it directly here, which imo. should be exactly what we do above just via the method.
  16.    
  17.     println(b)
  18.   }
  19. }
  20.  
  21.  
  22.  
  23. /*
  24.  
  25. scala> Test.run
  26. This should never print
  27. No exception yet.
  28. java.lang.ClassCastException: Test$Non cannot be cast to Test$Ext
  29.     at Test$.run(<console>:53)
  30.     at .<init>(<console>:40)
  31.  
  32. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement