Basic Kotlin syntax

Basic Kotlin syntax

basic grammar

define package name

Define the package name at the beginning of the source file:

package my.demo
import java.util.*

define function

Define a function that accepts two int parameters and returns an int:

fun sum(a: Int , b: Int) : Int{
    return a + b
}
fun main(args: Array<String>) {
    print("sum of 3 and 5 is ")
    println(sum(3, 5))
}

An expression function body and a self-deductive return value:

fun sum(a: Int, b: Int) = a + b
fun main(args: Array<String>) {
    println("sum of 19 and 23 is ${sum(19, 23)}")
}

The return type of Unit can be omitted:

fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}
fun main(args: Array<String>) {
    printSum(-1, 8)
}

define local variables

Declare constants:

fun main(args: Array<String>) {
    val a: Int = 1 // 立即初始化
    val b = 2 // 推导出Int型
    val c: Int // 当没有初始化值时必须声明类型
    c = 3 // 赋值
    println("a = $a, b = $b, c = $c")
}

variable:

fun main(args: Array<String>) {
    var x = 5 // 推导出Int类型
    x += 1
    println("x = $x")
}

Notes

与 java 不同的是 Kotlin 的 块注释一样

Use string templates

fun main(args: Array<String>) {
    var a = 1
    // 使用变量名作为模板:
    val s1 = "a is $a"
    a = 2
    // 使用表达式作为模板:
    val s2 = "${s1.replace("is", "was")}, but now is $a"
    println(s2)
}

Use conditional expressions

fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}
fun main(args: Array<String>) {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}

Use a function that returns a nullable value

fun parseInt(str: String): Int? {
    return str.toIntOrNull()
}
fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)
    // 直接使用 x*y 会产生错误因为它们中有可能会有空值
    if (x != null && y != null) {
        // x 和 y 将会在空值检测后自动转换为非空值
        println(x * y)
    }
    else {
        println("either '$arg1' or '$arg2' is not a number")
    }
}
fun main(args: Array<String>) {
    printProduct("6", "7")
    printProduct("a", "7")
    printProduct("a", "b")
}

use loop

for loop

fun main(args: Array<String>) {
    val items = listOf("apple", "banana", "kiwi")
    for (item in items) {
        println(item)
    }   
}

while loop

fun main(args: Array<String>) {
    val items = listOf("apple", "banana", "kiwi")
    var index = 0
    while (index < items.size) {
        println("item at $index is ${items[index]}")
        index++
    }
}

Use when expressions

fun describe(obj: Any): String =
when (obj) {
    1 -> "One"
    "Hello" -> "Greeting"
    is Long -> "Long"
    !is String -> "Not a string"
    else -> "Unknown"
}
fun main(args: Array<String>) {
    println(describe(1))
    println(describe("Hello"))
    println(describe(1000L))
    println(describe(2))
    println(describe("other"))
}

code style

Defaults to Java coding conventions, such as:

  • Use camel notation (avoid underscores in naming)
  • Type name capitalized
  • Lowercase methods and properties
  • Indent with four spaces
  • The public method needs to be documented so it can appear in the Kotllin Doc

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325646074&siteId=291194637