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

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 
主站蜘蛛池模板: 九龙县| 辽中县| 尤溪县| 通州区| 江门市| 彭山县| 教育| 探索| 凭祥市| 凤山县| 德江县| 湟源县| 乌鲁木齐县| 鸡东县| 永新县| 新绛县| 马公市| 潮州市| 三亚市| 莱阳市| 乌拉特中旗| 民和| 武威市| 大宁县| 浦北县| 汶上县| 永昌县| 泉州市| 剑河县| 德清县| 湟源县| 太仆寺旗| 大邑县| 本溪市| 邳州市| 山东省| 房山区| 合山市| 左云县| 陕西省| 融水|