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

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 
主站蜘蛛池模板: 松潘县| 宣武区| 从化市| 博野县| 台中县| 图木舒克市| 当涂县| 湖州市| 沾化县| 绥中县| 沁水县| 临朐县| 济南市| 于都县| 化德县| 石门县| 平潭县| 霍城县| 宁夏| 永年县| 民丰县| 东兴市| 高邑县| 公主岭市| 大悟县| 松桃| 青州市| 佛坪县| 车险| 铅山县| 蒲江县| 南皮县| 东莞市| 枝江市| 延长县| 永仁县| 刚察县| 张掖市| 昌平区| 巫山县| 尉氏县|