Kotlin basic syntax


Release date:2023-09-21 Update date:2023-10-13 Editor:admin View counts:305

Label:

Kotlin basic syntax

Kotlin file to .kt is a suffix.

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.testRunoob , the full name is com.runoob.main.Runoob.

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

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.*

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)
}

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
}

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
}

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

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..

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"

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)
  }
}

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
}

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)
}

Case test

fun main(args: Array<String>) {
    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
----------------

Powered by TorCMS (https://github.com/bukun/TorCMS).