- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 220字
- 2021-06-24 14:13:25
Type inference
Did you notice, in the previous section, that the type of the variable was not included when it was initialized? This is different to Java where the type of the variable must usually accompany its declaration. From Java 11 onward, local variables can also omit the type, but fields must always be annotated with the type.
Even though Kotlin is a strongly typed language, we don't always need to declare types explicitly. The compiler attempts to figure out the type of an expression from the information included in the expression. A simple val variable is an easy case for the compiler because the type is clear from the right-hand side. This mechanism is called type inference. This reduces boilerplate code, whilst keeping the type safety we expect of a modern language.
Values and variables are not the only places where type inference can be used. It can also be used in closures, where the type of the parameter(s) can be inferred from the function signature. It can also be used in single-line functions where the return value can be inferred from the expression in the function, as this example of increasing a number by 1 shows:
fun plusOne(x: Int) = x + 1
Sometimes, it is helpful to explicitly annotate the type:
val explicitType: Double = 12.3
- Advanced Splunk
- JavaScript前端開發(fā)模塊化教程
- Python程序設(shè)計(jì)教程(第2版)
- 解構(gòu)產(chǎn)品經(jīng)理:互聯(lián)網(wǎng)產(chǎn)品策劃入門寶典
- Vue.js快跑:構(gòu)建觸手可及的高性能Web應(yīng)用
- 編程珠璣(續(xù))
- Mastering C# Concurrency
- C++程序設(shè)計(jì)基礎(chǔ)教程
- 小程序,巧運(yùn)營:微信小程序運(yùn)營招式大全
- concrete5 Cookbook
- 深入淺出Serverless:技術(shù)原理與應(yīng)用實(shí)踐
- 高級(jí)語言程序設(shè)計(jì)(C語言版):基于計(jì)算思維能力培養(yǎng)
- iPhone應(yīng)用開發(fā)從入門到精通
- Web性能實(shí)戰(zhàn)
- IDA Pro權(quán)威指南(第2版)