Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala volatile types: How is @uncheckedStable unsafe?

Tags:

types

scala

I know that volatile types in Scala are there to model

the possibility that a type parameter or abstract type instance of a type does not have any non-null value

(http://www.scala-lang.org/files/archive/spec/2.11/03-types.html#volatile-types)

But what is the problem with this exactly? Is there an example which uses @uncheckedStable (see http://www.scala-lang.org/files/archive/spec/2.11/11-annotations.html#scala-compiler-annotations) which produces unsafe code?

like image 430
Fabian Schmitthenner Avatar asked Nov 08 '22 13:11

Fabian Schmitthenner


1 Answers

object Main extends App {      
  trait A { type T = Int }
  trait B { type T <: String }
  def f(b: B)(t: b.T) = t.length

  @annotation.unchecked.uncheckedStable val x: A with B = null
  val y: x.T = 0 // legal because x is A

  f(x)(y)
}

Now running...
[info] Running Main 
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

(Based on retronym's answer to Cannot override a type with non-volatile upper bound.)

like image 197
Alexey Romanov Avatar answered Nov 15 '22 07:11

Alexey Romanov