看板 PLT 關於我們 聯絡資訊
※ 引述《macbuntu (邀怪)》之銘言: : 看你的描述, 覺得你沒有真的了解我們在說的那個差異. : 上面這個狀況不應該 OK 是沒錯, 有趣的是它不 OK 的原因. : 在 Java 的設計下, compile time error 是這種: : interface A<T> { : T get(); : void set(T t); : } : void func(A<? extends Number> a) { : Number n = a.get(); : // compile time error, set(T) cannot safely bind to any type : a.set(n); : } : 但以 Scala 的設計, compile time error 是這種: : interface A<T> { : T get(); : void set(T t); : } : // compile time error, invariant type T cannot be covariant : void func(A<? extends Number> a) { : Number n = a.get(); : a.set(n); : } : 兩個結果都是不能 compile, 但仔細想想這兩個點微妙的差別吧, : 乍看或許覺得這兩個錯誤訊息說的是同樣的東西, 但其實是很不一樣的原因造成的. 你的意思是不是即使是這樣子,在 scala 設計中也應該是 compiler error(由 compiler 告訴 programmer invariant type 不能 covariant use)? // compile time error, invariant type T cannot be covariant void func(A<? extends Number> a) { Number n = a.get(); } 我寫了一個簡單的 scala 程式: object HelloWorld { def main(args: Array[String]) { var str_value:Value[String] = new Value[String]("Hello, World!"); var int_value:Value[Integer] = new Value[Integer](87); showValue(str_value); showValue(int_value); } // def showValue[V >: Any](obj:Value[V]) { // println(obj.get); // } // def showValue(obj:Value[Any]) { // println(obj.get); // } } class Value[T](init:T) { private var x:T = init def get:T = { x } def set(x:T) = { this.x = x} } 我發現我沒有辦法寫出一個 showValue method 可以讓我單純地把任一個 Value instance 所持有的 value 輸出,這是我欠缺某觀念,所以我寫不出來?還是? 這一點是我不滿意 scala 關於 subtyping variance 語法的原因之一。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.129.21