5

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?

Fabian Schmitthenner
  • 1,696
  • 10
  • 22

1 Answers1

1
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.)

Community
  • 1
  • 1
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • hm, but this seems to "work" even without @annotation.unchecked.uncheckedStable and if I'm reading the spec correctly (http://www.scala-lang.org/files/archive/spec/2.11/03-types.html#volatile-types ), A with B isn't even volatile – Fabian Schmitthenner Jun 24 '16 at 20:00
  • Yes, you are right. And if I try to modify his first answer instead, `uncheckedStable` doesn't seem to work at all: http://scastie.org/20577 – Alexey Romanov Jun 25 '16 at 02:56
  • I'm removing the check then since this isn't answering the reason for type volatility, just makes it more confusing – Fabian Schmitthenner Jun 25 '16 at 18:00
  • Perhaps you should ask at https://groups.google.com/forum/#!forum/scala-user as well? And post the answer here if you get one. – Alexey Romanov Jun 25 '16 at 21:06