Clojure nil vs Java null?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/691925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Clojure nil vs Java null?
提问by Jason Baker
Forgive me if I'm being obtuse, but I'm a little bit confused by the documentation about nil in Clojure. It says:
原谅我,如果我很迟钝,但我对 Clojure 中关于 nil 的文档有点困惑。它说:
nil has the same value as Java null.
nil 与 Java null 具有相同的值。
Does this mean that they're the same thing or are they different somehow? And does a NullPointerException mean that a Java null was encountered or would I also get this if nil was encountered?
这是否意味着它们是相同的东西还是它们有什么不同?并且 NullPointerException 是否意味着遇到了 Java null 或者如果遇到 nil 我也会得到这个?
采纳答案by John Ellinwood
From Learning Clojure
"In most Lisp dialects, there is a value semi-equivalent to Java null called nil. In Clojure, nil is simply Java's null value, end of story."
“在大多数 Lisp 方言中,有一个半等价于 Java null 的值,称为 nil。在 Clojure 中,nil 只是 Java 的 null 值,故事结束。”
Since Clojure compiles to java bytecode, it sounds like any reference to nil is just a null object reference in the underlying JVM. Your NPEs from executing Clojure are the result of accessing nil.
由于 Clojure 编译为 java 字节码,听起来任何对 nil 的引用都只是底层 JVM 中的空对象引用。执行 Clojure 的 NPE 是访问 nil 的结果。
回答by Brian Carper
From the Clojure source code, lang/LispReader.java:
从 Clojure 源代码,lang/LispReader.java:
static private Object interpretToken(String s) throws Exception{
if(s.equals("nil"))
{
return null;
}
From lang/RT.java:
来自lang/RT.java:
static public void print(Object x, Writer w) throws Exception{
{
...
if(x == null)
w.write("nil");
So nilis Clojure's representation for the underlying platform's null. nilshows up nowhere else in the Java source for Clojure. The only difference between niland nullis that one is Clojure and the other is Java, but they're essentially aliases, converted back and forth seamlessly as needed by the reader and printer when going from Clojure to Java to Clojure.
所以nil是Clojure的对底层平台的代表null。 nil在 Clojure 的 Java 源代码中没有其他地方出现。nil和之间的唯一区别null是,一个是 Clojure,另一个是 Java,但它们本质上是别名,在从 Clojure 到 Java 再到 Clojure 时,根据阅读器和打印机的需要无缝地来回转换。
Yeah, nilcan cause NullPointerExceptions. Try calling any Java method on nil, you'll get an NPE, e.g.
是的,nil可以导致NullPointerExceptions。尝试在 上调用任何 Java 方法nil,您将获得一个 NPE,例如
(.tostring nil)
The Clojure source code is pretty easy to read when it comes to things like this, give it a look.
Clojure 源代码在涉及到这样的事情时非常容易阅读,请看一看。

