What is difference between Null, Nil and Nothing?

旧街凉风 提交于 2021-02-19 01:48:06

问题


I am learning Scala and am a bit confounded by the difference between next types: 'Null', 'Nil' and 'Nothing'.

Can someone please help explain the difference to me? From what i gather, "Nil" is used to describe an empty list.


回答1:


Nothingness in Scala

There are 7 cases where you want to represent the concept of nothingness in Scala.

Nil - Used for representing empty lists, or collections of zero length. For sets you can use Set.empty

None - One of two subclasses of the Optional type, the other being Some. Very well supported by the Scala collections.

Unit - Equivalent to Java's void which is used for functions that don't have a return type

Nothing - A trait. It is a subtype of all other types, but supertype of nothing. It is like the leaf of a tree. No instances of Nothing.

Null - A trait. Not recommended to be used.

null - An instance of the trait, similarly used as the Java Null. Not recommended to be used.

Best Practices

  • If you have code that is returning null, change it to return an Optional.
  • If you need to have an uninitialized variable, using Optional, or an empty list/collection instead of null
  • *

For best practices recommendation, please see https://alvinalexander.com/scala/scala-null-values-option-uninitialized-variables

Why is null so hated?

  • Please watch Tony Hoare's Billion Dollar Mistake
  • Null pointer errors are hard to debug



回答2:


In scala null is realy bad, you must use Optional[T].

We have Nil which is a empty list to be able to do 1 :: Nil to create a list that contain only 1.

And, Nothing is a subtype of every type. In other world, is a object that represent null.



来源:https://stackoverflow.com/questions/46796032/what-is-difference-between-null-nil-and-nothing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!