Usages of Null / Nothing / Unit in Scala

2020-01-27 09:54发布

I've just read: http://oldfashionedsoftware.com/2008/08/20/a-post-about-nothing/

As far as I understand, Null is a trait and its only instance is null.

When a method takes a Null argument, then we can only pass it a Null reference or null directly, but not any other reference, even if it is null (nullString: String = null for example).

I just wonder in which cases using this Null trait could be useful. There is also the Nothing trait for which I don't really see any more examples.


I don't really understand either what is the difference between using Nothing and Unit as a return type, since both doesn't return any result, how to know which one to use when I have a method that performs logging for example?


Do you have usages of Unit / Null / Nothing as something else than a return type?

标签: scala
8条回答
We Are One
2楼-- · 2020-01-27 10:34

Do you have usages of Unit / Null / Nothing as something else than a return type?


Unit can be used like this:

def execute(code: => Unit):Unit = {
  // do something before
  code
  // do something after
}

This allows you to pass in an arbitrary block of code to be executed.


Null might be used as a bottom type for any value that is nullable. An example is this:

implicit def zeroNull[B >: Null] =
    new Zero[B] { def apply = null }

Nothing is used in the definition of None

object None extends Option[Nothing]

This allows you to assign a None to any type of Option because Nothing 'extends' everything.

val x:Option[String] = None
查看更多
够拽才男人
3楼-- · 2020-01-27 10:36

Nothing is often used implicitly. In the code below, val b: Boolean = if (1 > 2) false else throw new RuntimeException("error") the else clause is of type Nothing, which is a subclass of Boolean (as well as any other AnyVal). Thus, the whole assignment is valid to the compiler, although the else clause does not really return anything.

查看更多
登录 后发表回答