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

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.

主站蜘蛛池模板: 遂平县| 淳化县| 思茅市| 永川市| 改则县| 新丰县| 上蔡县| 马鞍山市| 太谷县| 台南县| 金昌市| 蓬溪县| 宣武区| 沙洋县| 叶城县| 永州市| 伊春市| 蒲城县| 永济市| 明光市| 界首市| 沙坪坝区| 丰台区| 石景山区| 苍南县| 曲水县| 巴林左旗| 咸丰县| 桐柏县| 平南县| 栖霞市| 监利县| 兰考县| 黄陵县| 岗巴县| 赤峰市| 南和县| 松桃| 抚宁县| 武清区| 永仁县|