An exception throw has type `Nothing`?

馋奶兔 提交于 2019-12-06 02:30:17

It is saying that half is not found. However, based on the book, I assume it should say it is defined and it is with type Nothing.

If you re-read that paragraph, you'll see that the type of half shouldn't be Nothing, it should be Int:

The type of the whole if expression is then the type of that branch which does compute something.

The branch which does compute a value produces the type Int. You can prove this by defining half as a method and not a value:

scala> def half = if (n % 2 == 0) n / 2 else throw new RuntimeException("n must be even")
half: Int

If you actually want to see that throw has type Nothing, add it in your IDE and make it show the type:

val exception: Nothing = throw new RuntimeException("n must be even")

Regarding half, it isn't found because it's declaration throws an exception, which makes the REPL unable to bind a value to it.

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