- Learning Scala Programming
- Vikash Sharma
- 167字
- 2021-06-30 19:07:51
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:

With this, it's important to understand that Type Inference plays an important role in Scala's ecosystem.
- C++ Primer習題集(第5版)
- Vue 3移動Web開發(fā)與性能調(diào)優(yōu)實戰(zhàn)
- Raspberry Pi for Python Programmers Cookbook(Second Edition)
- 名師講壇:Java微服務架構實戰(zhàn)(SpringBoot+SpringCloud+Docker+RabbitMQ)
- TypeScript實戰(zhàn)指南
- Bootstrap 4:Responsive Web Design
- Python編程實戰(zhàn)
- Django實戰(zhàn):Python Web典型模塊與項目開發(fā)
- Instant Debian:Build a Web Server
- Python GUI Programming Cookbook(Second Edition)
- PHP Microservices
- RESTful Web API Design with Node.js(Second Edition)
- ASP.NET本質(zhì)論
- Test-Driven Java Development(Second Edition)
- 嵌入式網(wǎng)絡編程