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

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.

主站蜘蛛池模板: 吴川市| 越西县| 九江县| 金山区| 海安县| 普兰店市| 灯塔市| 翁牛特旗| 塔城市| 望谟县| 苏州市| 朝阳市| 岳阳县| 织金县| 烟台市| 集安市| 德庆县| 托克逊县| 吉安市| 泽普县| 上蔡县| 航空| 苏尼特左旗| 简阳市| 闵行区| 河池市| 进贤县| 贵州省| 弥勒县| 玛沁县| 长顺县| 大关县| 柞水县| 都兰县| 大方县| 安化县| 镇赉县| 四平市| 固安县| 类乌齐县| 上思县|