- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 249字
- 2021-06-10 18:49:19
Type inference
Kotlin is a statically-typed language. It executes the type inference for us, so we don't have to specify types. Consider the code for 3a_TypeInference.kts:
val message = "Hi there"
println(message)
When we run this code, we get the following output:
We can also explicitly specify the type. Consider the following code:
val message : String = "Hi there"
println(message)
This is an example of creating a variable of the String type and printing it in the console. This looks like Scala syntax and it is quite different from what we do in Java.
In Java, we would write this as follows:
String message = "Hi there";
Languages such as Kotlin emphasize that the name of a variable is more important than the nature of the variable. Kotlin puts the name of a variable or constant first and the type after in the var declaration syntax. The type is, in fact, optional; we don't have to specify it. We might think that this is the same as the dynamic type, where the type is resolved during runtime. Kotlin, however, actually infers the type at compile time.
Kotlin uses the String class from the JDK library. We can query the class that it uses as follows:
val message = "Hi there"
println(message.javaClass)
The output is as follows:
As a general rule, it's a good idea to specify type information when we write public-facing interfaces and, when using local variables, we can let the language infer the type.
- Learning Single:page Web Application Development
- 極簡算法史:從數學到機器的故事
- 計算思維與算法入門
- 編程的修煉
- 微信公眾平臺開發:從零基礎到ThinkPHP5高性能框架實踐
- 大數據分析與應用實戰:統計機器學習之數據導向編程
- RabbitMQ Essentials
- Webpack實戰:入門、進階與調優
- Python算法詳解
- 創意UI:Photoshop玩轉APP設計
- 從程序員角度學習數據庫技術(藍橋杯軟件大賽培訓教材-Java方向)
- 區塊鏈架構之美:從比特幣、以太坊、超級賬本看區塊鏈架構設計
- 深入淺出Python數據分析
- Scratch從入門到精通
- Penetration Testing with the Bash shell