3.6. Kotlin basic syntax

发布时间 : 2025-10-25 13:34:27 UTC      

Page Views: 10 views

Kotlin file to .kt is a suffix.

3.6.1. Package declaration #

The code file usually begins with the declaration of the package:

package com.runoob.main import java.util.* fun test() {} class Runoob {} 

kotlin source files do not need matching directories and packages, and source files can be placed in any file directory.

In the above example test() , the full name is com.runoob.main.test Runoob , the full name is com.runoob.main.Runoob .

If no package is specified, the default is default bag.

3.6.2. Default import #

Multiple packages are imported into each by default Kotlin File:

  • kotlin.*

  • kotlin.annotation.*

  • kotlin.collections.*

  • kotlin.comparisons.*

  • kotlin.io.*

  • kotlin.ranges.*

  • kotlin.sequences.*

  • kotlin.text.*

3.6.3. Function definition #

Function definitions use keywords fun , parameter format is: parameter:type

fun sum(a: Int, b: Int): Int { // Int parameter, return value Int return a + b } 

The expression, as the body of the function, returns the automatic inferenceof the type:

fun sum(a: Int, b: Int) = a + b public fun sum(a: Int, b: Int): Int = a + b // The public method must explicitly state the return type 

A function with no return value (similar to Java in void ):

fun printSum(a: Int, b: Int): Unit { print(a + b) } // If it returns the Unit type, it can be omitted (also for public methods): public fun printSum(a: Int, b: Int) { print(a + b) } 

3.6.4. Variable length parameter function #

The variable length argument of the function can be used with the vararg keyword to identify:

fun vars(vararg v:Int){ for(vt in v){ print(vt) } } // test fun main(args: Array<String>) { vars(1,2,3,4,5) // Output 12345 } 

3.6.5. Lambda (anonymous function) #

lambda examples of expression usage:

// test fun main(args: Array<String>) { val sumLambda: (Int, Int) -> Int = {x,y -> x+y} println(sumLambda(1,2)) // Output 3 } 

3.6.6. Define constants and variables #

Variable definition: var keyword

Var<identifier>:<type>=<initialization value> 

Immutable variable definition: val keyword, a variable that can only beassigned once (similar to Java medium final modified variables)

Val<identifier>:<type>=<initialization value> 

Both constants and variables can have no initialization value, but must be initialized before referencing

The compiler supports automatic type determination, that is, it can be declared without specifying a type, which can be judged by the compiler.

val a: Int = 1 val b = 1 // The system automatically infers that the variable type is Int val c: Int // If not initialized at declaration time, variable type must be provided c = 1 // definitely assigned var x = 5 // The system automatically infers that the variable type is Int x += 1 // Variable modifiable 

3.6.7. Annotation #

Kotlin single-line and multi-line comments are supported. Examples are as follows:

// This is a single line comment /* This is a multi line block annotation. */ 

Unlike Java , block annotations in Kotlin allow nesting..

3.6.8. String template #

$ represents a variable name or value

$varName represents the value of a variable

${varName.fun()} method that represents the variable returns a value:

var a = 1 // Simple name in template: val s1 = "a is $a" a = 2 // Any expression in the template: val s2 = "${s1.replace("is", "was")}, but now is $a" 

3.6.9. NULL inspection mechanism #

Kotlin empty security design for parameters that can be declared to be nullable should be processed by null judgment when in use. There are two ways to handle the null security design, adding the field after the field. !! like Java , the same empty exception is thrown, and another field is added. ? can not be processed, the return value is null or cooperate ?: with short judgment processing

//After the type, add? Indicates that it can be empty var age: String? = "23" //Throwing a null pointer exception val ages = age!!.toInt() //Returning null without processing val ages1 = age?.toInt() //Returning -1 when age is empty val ages2 = age?.toInt() ?: -1 

When a reference may be null value, the corresponding type declaration must be explicitly marked as null .

When str returns when the content of the string in is not an integer null :

fun parseInt(str: String): Int? { // ... } 

The following example shows how to use a return value for null functionof:

fun main(args: Array<String>) { if (args.size < 2) { print("Two integers expected") return } val x = parseInt(args[0]) val y = parseInt(args[1]) // Directly using 'x * y' can cause errors as they may be null if (x != null && y != null) { // After checking for null values, the types of x and y will be automatically converted to non null variables print(x * y) } } 

3.6.10. Type detection and automatic type conversion #

We can use it. is operator to detect whether an expression is an instance of a type similar to the one in Java instanceof keywords).

fun getStringLength(obj: Any): Int? { if (obj is String) { // After making type judgments, obj will be automatically converted to a String type by the system return obj.length } //There is another method here, different from instanceof in Java, to use is // if (obj !is String){ // // XXX // } // The obj here is still a reference of type Any return null } 

Or

fun getStringLength(obj: Any): Int? { if (obj !is String) return null // In this branch, the type of `obj` will be automatically converted to `String` return obj.length } 

It’s even okay.

fun getStringLength(obj: Any): Int? { // On the right side of the `&&` operator, the type of `obj` will be automatically converted to `String` if (obj is String && obj.length > 0) return obj.length return null } 

3.6.11. Interval #

Interval expressions are in the form of operators .. of rangeTo function supplemented by in and !in form.

The interval is defined for any comparable type, but for integer primitive types, it has an optimized implementation. Here are some examples of using intervals:

for (i in 1..4) print(i) // Output “1234” for (i in 4..1) print(i) // Output nothing if (i in 1..10) { // Equivalent to 1 <= i && i <= 10 println(i) } // Use step to specify step size for (i in 1..4 step 2) print(i) // Output “13” for (i in 4 downTo 1 step 2) print(i) // Output “42” // Using the until function to exclude end elements for (i in 1 until 10) { // i in [1, 10) except 10 println(i) } 

3.6.12. Case test #

fun main(args: Array) { print("Loop output:") for (i in 1..4) print(i) // Output “1234” println("\n----------------") print("Set Step Size:") for (i in 1..4 step 2) print(i) // Output “13” println("\n----------------") print("use downTo:") for (i in 4 downTo 1 step 2) print(i) // Output “42” println("\n----------------") print("use until:") // Using the until function to exclude end elements for (i in 1 until 4) { // i in [1, 4) except 4 print(i) } println("\n----------------") }    

Output result:

Loop output: 1234 ---------------- Set step size: 13 ---------------- Using downTo: 42 ---------------- Use until: 123 ---------------- 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。