What have you found for these years?

2009-03-14

R: [分享] 原來 Void 可以這樣用 (2)

Scala 看起來不錯,看最近有沒有空玩一下...
┌─────────────────────────────────────┐
│ 文章代碼(AID): #19ki7zXT (java) [ptt.cc] Re: [分享] 原來 Void 可以這樣用 │
│ 文章網址: http://www.ptt.cc/bbs/java/M.1236976125.A.85D.html
│ 這一篇文章值 405 銀 │
└─────────────────────────────────────┘
作者 godfat (godfat 真常) 看板 java
標題 Re: [分享] 原來 Void 可以這樣用
時間 Sat Mar 14 04:28:43 2009
───────────────────────────────────────

板名再換一下,說真的,有個版叫 PLT... XD

[...略]

Scala 我不熟哩,不過經你一提我大概看了一下 Null 和 Nothing.

http://www.scala-lang.org/docu/files/api/scala/Null.html
http://www.scala-lang.org/docu/files/api/scala/Nothing.html

而 Null 和 Nothing 當然是 programmer 可以用的東西。
至於怎麼用呢?上面那兩個連結其實就已經說明了。

Null 應該很好理解吧?就像我上一篇提到的,他只有唯一的一個 instance,
就是 null, 而他也同時是所有 reference type 的 subtype,
所以在原本 sbrhsieh 的例子裡:
public interface SomeInterface {
public java.util.List visit(Node node); // return type 不為 Object
}

實作就是:

class SomeVisitor implements SomeInterface{
public Null visit(Node node){
return null; // 這就是唯一選擇了
}
}

這邊跟你原本用 Void 是一樣的。

java.lang.Object
extended by java.lang.Void

你只要把 Null 想像成 Void, 而 java.util.List 想像成 Object 就行了。
只是 Void 只接受 Object, 因為那是他唯一的 parent.
而 Null 接受任何 reference type (也就是不接受 value type),
也不接受 Nothing, 因為 Nothing 比 Null 更底層,其他一律接受。
因為他的 parent 就是以上這些東西。

也像是我原本 C++ 裡寫的 None<T> 只是更 general, 因為 None<T>
和 None<S> 又是不同的,但是 Scala 的 Null 只有一個!


*


Nothing 就完全是另一回事了。連結上簡單的一句話也是一個範例:

For instance, the Scala library defines a value Nil of type
List[Nothing]. Because lists are covariant in Scala, this makes
Nil an instance of List[T], for any element type T.

可以先看到 List 的定義:

sealed abstract class List[+A]
extends Seq[A] with Product

先不用管 Seq[A] 和 Product 是什麼,這邊的 List[+A] 表示 list 有一個
covariant subtype relationship, 意思是假使 Integer 是 Object 的
subtype, 則 List[Integer] 也會是 List[Object] 的 subtype.

因此我們定義 Nil 是 List[Nothing] 的 singleton object:

case object Nil
extends List[Nothing]

而由於 Nothing 是所有 type 的 subtype, 所以 List[Nothing] 也是
所有 List[T] 的 subtype. 這意味著儘管我們有無窮多種 List[???],
但是這些 List 的 empty/base value, whatever, 只有一個,就是 Nil.

因此我們可以寫:

val any: List[Any] = Nil // Java 語法的話:List[Any] any = Nil

也可以寫:

val int: List[Int] = Nil // Java 語法的話:List[Int] int = Nil

因為 Nil 是 List[Nothing] 的 instance, 而 List[Nothing] 是
List[Any] 的 subtype, 也是 List[Int] 的 subtype.

ref:
http://www.scala-lang.org/node/128

==
文件滿完整的哩,改天來玩玩看...
另外還有個 JVM 語言是 Clojure, http://clojure.org/
這是 Lisp 的變種,最近好像滿流行的。
不過用起來的感覺我覺得有點怪,Scala 比較漂亮...

--
Hear me exalted spirits. Hear me, be you gods or devils, ye who hold
dominion here:
I am a wizard without a home. I am a wonderer seeking refuge.

Sacrifice

--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.135.28.18

2 retries:

Hinoris said...

對、委託拍賣助手在日本拍賣上買的。

從現在開始算起,到我可以拿到貨為止估計還有兩、三個星期。這時間應該夠我把手上的試玩版玩一玩了。

Lin Jen-Shin (godfat) said...

拍賣助手 XD
不過東方系列我只玩過妖妖夢一點而已
打過一次就不想打第二次了...

Post a Comment

Note: Only a member of this blog may post a comment.



All texts are licensed under CC Attribution 3.0