官术网_书友最值得收藏!

Null and Nothing

Null and Nothing are called Bottom types in Scala. Why do we need these Bottom types? Take a look at the code snippet:

def checkIF10AndReturn20(x: Int): Int =  {
if(x == 10)
x * 2
else
throw new Exception("Sorry, Value wasn't 10")
}

The method checkIf10AndReturn20 expects a returned value of Int type, but what's happening here is different. If the passed argument value is not 10, we are throwing an exception, yet still the compiler is OK with our code. How can this be possible?

This is because of Type Inference. It always looks for common types in both branches of an if statement, so if in the other branch, the type extends everything, then the inferred type will automatically be the first one. In Scala, Nothing is a subtype of everything, hence the inferred type automatically becomes of type Int. Let's visualize this:

Visualizing Types Inferred

With this, it's important to understand that Type Inference plays an important role in Scala's ecosystem.

主站蜘蛛池模板: 澄迈县| 沐川县| 云霄县| 武陟县| 兴山县| 改则县| 文登市| 伽师县| 沂源县| 手游| 集贤县| 红原县| 吴桥县| 鸡泽县| 无为县| 苍山县| 会同县| 弥渡县| 淮北市| 肇源县| 怀来县| 祁东县| 凤城市| 万全县| 错那县| 吐鲁番市| 陆河县| 仙桃市| 莱西市| 双鸭山市| 溧水县| 雅江县| 内丘县| 隆子县| 海安县| 宜昌市| 闸北区| 清新县| SHOW| 阳谷县| 墨玉县|