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

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 
主站蜘蛛池模板: 安吉县| 南溪县| 沽源县| 康平县| 临潭县| 武宁县| 锡林浩特市| 汕头市| 宜君县| 北辰区| 和平区| 伽师县| 凤山市| 牙克石市| 北安市| 永泰县| 香河县| 景东| 和政县| 阳信县| 微山县| 绍兴市| 南开区| 汝城县| 青冈县| 河间市| 宁远县| 新营市| 东至县| 永定县| 清河县| 金堂县| 瑞金市| 正定县| 平南县| 浑源县| 尉氏县| 辛集市| 连州市| 藁城市| 高阳县|