What's the difference between undefined in Haskell and null in Java?

后端 未结 2 1804
逝去的感伤
逝去的感伤 2021-01-31 07:12

Both are terms whose type is the intersection of all types (uninhabited). Both can be passed around in code without failing until one attempts to evaluate them. The only differe

2条回答
  •  感动是毒
    2021-01-31 08:16

    Your description isn't quite correct. You're saying null can't be evaluated. However since java is an eager language, this would mean that f(null) would throw an NPE no matter what the definition of f is (because method arguments are always evaluated before the method runs).

    The only reason that you can pass around undefined in haskell without getting an exception is that haskell is lazy and does not evaluate arguments unless needed.

    One further difference between undefined and null is that undefined is a simple value defined in the standard library. If it weren't defined in the standard library you could define it yourself (by writing myUndefined = error "My Undefined for example).

    In Java null is a keyword. If there were no null keyword, you wouldn't be able to define it (doing the equivalent of the haskell definition, i.e. Object myNull = throw(new Exception()), wouldn't work because the expression would be evaluated right there).

提交回复
热议问题