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

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.

主站蜘蛛池模板: 东城区| 太白县| 临清市| 苍南县| 兰坪| 昂仁县| 湘潭县| 临漳县| 龙山县| 安平县| 定西市| 兴仁县| 郑州市| 探索| 石棉县| 苍南县| 岐山县| 互助| 方山县| 炎陵县| 永胜县| 射阳县| 泸州市| 基隆市| 太和县| 平乐县| 香港| 正安县| 隆化县| 内黄县| 华宁县| 平南县| 齐齐哈尔市| 聂荣县| 镇坪县| 紫云| 辽宁省| 佛教| 唐海县| 昌都县| 克东县|