Understanding of scala.Nothing type

拥有回忆 提交于 2020-05-13 09:04:56

问题


According to the scala specification, scala.Nothing type - buttom for all types. Type "Nothing" exists but instance of Nothing does not exists.

How it works:

def ??? : Nothing = throw new NoImplementedError
def sys.error(message: String): Nothing = throw new RuntimeException()
def sys.exit(status: Int): Nothing = {...}

But in fact, all of mentioned methods return exception. Excepted def sys.exit Could you please clarify more about type Nothing. Any examples, explanations.

Thanks!


回答1:


def ??? : Nothing = throw new NoImplementedError

does not return an exception, it throws an exception which is not the same thing. Exceptions are a control-flow mechanism which causes control to immediately jump to the nearest installed handler within the call stack. This means that in

val x = ???

x will never be assigned a value, so x can have any type at all. This type is Nothing in the scala type system which is the subtype of all types.

Non-termination also has type nothing since it also never returns a value e.g.

def loop(): Nothing = loop()

val x: Int = loop()

is therefore allowed since x will never be assigned.




回答2:


In Scala absolutely everything needs to have a return type.

println for example have the return type Unit because it's a unit of calculations that returns no value.

If everything needs to have a return type then, how would you implement a function like ???, so that it can be used by any function, no matter what type it needs to return?

Well that is what Nothing is for, it's a subtype of every other types (as Any is the top type of every other type), so a function that returns Nothing can be used anywhere and the type system will always stay consistent.

As you already noticed functions returning Nothing never return a value. That is because there is no value instenciable for Nothing.
You can see it as a way to make the compiler "happy" for functions that only throws or stop the app or loop forever.


In case you wonder why we don't use Unit instead of Nothing, here is an example:

def notYetImplemented: Unit = throw new Exception() 
def myFunc: String = notYetImplemented

This will not compile because Unit is not a String or a subtype of String. So you will need to do:

def myFunc: String = {
  notYetImplemented
  null
}

Which is not very convenient and for us to write a value to return even taught we will never reach this code.

Cheers



来源:https://stackoverflow.com/questions/35848904/understanding-of-scala-nothing-type

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