【问题标题】:Scala volatile types: How is @uncheckedStable unsafe?Scala volatile 类型:@uncheckedStable 如何不安全?
【发布时间】:2016-06-24 14:26:26
【问题描述】:

我知道 Scala 中的 volatile 类型可以用来建模

类型参数或类型的抽象类型实例没有任何非空值的可能性

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

但这到底有什么问题呢?有没有使用@uncheckedStable(见http://www.scala-lang.org/files/archive/spec/2.11/11-annotations.html#scala-compiler-annotations)产生不安全代码的例子?

【问题讨论】:

    标签: scala types


    【解决方案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
    

    (基于对Cannot override a type with non-volatile upper bound 的回溯。)

    【讨论】:

    • hm,但即使没有 @annotation.unchecked.uncheckedStable 并且如果我正确阅读规范(scala-lang.org/files/archive/spec/2.11/…),这似乎也可以“工作”,A 和 B 甚至都不是易变的跨度>
    • 是的,你是对的。如果我尝试修改他的第一个答案,uncheckedStable 似乎根本不起作用:scastie.org/20577
    • 我正在删除检查,因为这不能回答类型波动的原因,只会让它更加混乱
    • 也许您也应该在groups.google.com/forum/#!forum/scala-user 询问?如果您得到答案,请在此处发布答案。
    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    相关资源
    最近更新 更多