Basic syntax of Kotlin series

Tags: Kotlin Kotlin basic syntax


content:

Brief description:

Introducing the basic syntax of Kotlin, let's first understand the programming style of Kotlin as a whole.


1. Package declaration

Defining packages in Kotlin is a bit different from Java. In Kotlin, the directory and package structure do not need to match, and the source code of Kotlin can be anywhere on the disk.

  • 1. Package declaration

    Source files usually start with a package declaration, as in Java.

    package com.mikyou.kotlin
    
    /**
    * Created by mikyou on 2017/10/12.
    */
    fun main(args: Array<String>) {
    println("hello kotlin")
    }
    
  • 2, the default import of the package

    There are several packages that are imported into every Kotlin file by default.

Second, the definition of the function

  • 1. The function definition uses the keyword "fun", the function parameter format is: "parameter: type", and the function return value type "fun(...): Int"

    fun sum(a: Int, b: Int, c: Int): Int {
        return a + b + c
    }
  • 2. The expression is used as the body of the function, and the type of the return value can be omitted. You can use the type deduction function of Kotlin to infer the type of the return value of the function.

    fun sum(a: Int, b: Int, c: Int) = a + b + c
    
  • 3. Functions with no return value (similar to the return value of void empty type in Java)

    fun printSum(a: Int, b: Int, c: Int): Unit{
     println(a + b +c)
    }

    or omit the Unit type

    fun printSum(a: Int, b: Int, c: Int){
    println("sum = ${a + b + c}")
    }
  • 4. Variable-length parameter functions can use the "vararg" keyword to identify public void setData(Object... objects) in Java.

    fun vars(vararg args: Int) {
    for (arg in args) {
        print(arg)
    }
    }
  • 5. lambda (anonymous function)

    val sumLambda: (Int, Int, Int) -> Int = { a, b, c -> a + b + c }
    

    test

    println("sum = ${sumLambda(1, 6, 7)}")

3. Constants and Variables

Both constants and variables can have no initialization value, but they must be initialized before reference. The compiler supports automatic type judgment, that is, the type can not be specified when declaring, and the compiler will judge. The type of the variable must be provided if it is not initialized at the time of declaration

  • 1. Definition of variable variable: var keyword

    var <variable name> : <variable type> = <initial value>

    var sum: Int = 3
    sum = 8
    
    //由于编译支持类型推导可以省略Int类型
    
    var sum = 3
    sum = 8
  • 2. Definition of immutable variables: val keyword, which cannot be assigned twice, similar to the final type in Java

    val <const name> : <constant type> = <initial value>

    val sum: Int //没有赋值初始化之前必须指定类型
    
    sum = 5

4. Notes

Kotlin supports single-line and multi-line comments, similar to Java.

5. String Template

  • 1. Simple name in template

    fun main(args: Array<String>){
     var a = 1
     var s1 = "a is $a" 
    }
  • 2. Arbitrary expressions in templates

    fun main(args: Array<String>){
     var a = 1
     a = 2
     val s2 = "${s1.replace("is","was")}, but now is $a"
    }

6. Use conditional expressions

  • Use if expression instead of ternary operator in java

    fun maxOf(a: Int, b: Int): Int{
       if(a > b){
    
          return a
    
       }else{
    
          return b
       }
    }
    
    fun main(args: Array<String>){
    
      println(maxOf(1,5))
    
    }
    

    In Kotlin, if expressions have return values, so they can be simplified to the following form.

    fun maxOf(a: Int, b: Int) = if (a > b) a else b
    
    fun main(args: Array<String>){
    
      println(maxOf(1,5))
    
     }
    

Seven, NULL check mechanism

Kotlin's null safety design For parameters declared as nullable, null judgment processing is required when using them. There are two processing methods. Add !! after the field and throw a null exception like Java, and add ? after the other field. Processing return value is null or cooperate?: Short judgment processing

     //类型后面加?表示可为空
    var age: String? = "23" 
    //字段后面加"!!"抛出空指针异常
    val ages = age!!.toInt()
    //字段后面加”?“不做处理返回 null
    val ages1 = age?.toInt()
    //使用”?:“ 表示age为空返回-1
    val ages2 = age?.toInt() ?: -1
  • 1. When a reference may be a null value, the corresponding type declaration must be clearly marked with "?" after the type to indicate that it can be null.
    Returns null when the string content in str is not an integer:

    fun main(args: Array<String>) {
    
        if (args.size < 2){
            println("Two Integers Expected")
            return
        }
    
        val x = parseInt(args[0])
        val y = parseInt(args[1])
    //    println(x + y) 由于标识了可能为null,直接使用x + y在编译器看来是非法,需要去做非空判断
    
        if (x != null && y != null){
            println(x + y)
        }
    
    }
    
    fun parseInt(s: String): Int?{//表示当前函数返回值可能为null,就必须在类型后面标识"?"
        return s.toInt()
    }
    

Eight, type detection and automatic type conversion

We can use the is operator to check if an expression is an instance of a certain type (similar to the instanceof keyword in Java).

fun getStringLength(obj: Any): Int? {
  if (obj is String) {
    // 做过类型判断以后,obj会被系统自动转换为String类型
    return obj.length 
  }

  //在这里还有一种方法,与Java中instanceof不同,使用!is
  // if (obj !is String){
  //   // XXX
  // }

  // 这里的obj仍然是Any类型的引用
  return null
}

or

fun getStringLength(obj: Any): Int? {
  if (obj !is String)
    return null
  // 在这个分支中, `obj` 的类型会被自动转换为 `String`
  return obj.length
}

It can even be like this

fun getStringLength(obj: Any): Int? {
  // 在 `&&` 运算符的右侧, `obj` 的类型会被自动转换为 `String`
  if (obj is String && obj.length > 0)
    return obj.length
  return null
}

9. Interval

Use the in operator to detect whether a number is in the specified range. The range expression has the operator form ".." rangeTo function auxiliary in and !in combination. Ranges can support any comparable type, and for native integers, there is an optimized implementation internally.

  • 1. Check if a number is within a specified range

    val x = 10
    val y = 9
    if (x in 1..y + 1) {//表示x是否在1~y+1范围内。
        println("fits in range")
    }
  • 2. Check whether a number is outside the specified range

    val list = listOf("a", "b", "c")
    if (-1 !in 0..list.lastIndex) {
        println("-1 is out of range")
    }
    
    if (list.size !in list.indices) {
        println("list size is out of valid list indices range too")
    }
  • 3. Interval iteration

    for(x in 1..10){//相当于 x >= 1 && x <= 10
       println(x)
    }

    or

    fun printList(num: Int){
    
    for(i in 1..num){//相当于 i >= 1 && i <= num
       print(i)
      }
    }
    

    Use the until function to exclude ending elements

    for (i in 1 until 10) {   // i in [1, 10) 排除了 10,相当于 i >= 1 && i < 10
     println(i)
    } 
  • 4. Sequence iteration

    for(x in 1..100 step 2){//递增数列迭代,每次间隔步长是2;1,3,5,7...
        println(x)
    }
    
    for(x in 9 downTo 0 step 3){//递减数列迭代,每次间隔步长是3;9,6,3,0
        println(x)
     }    

10. Using Collections

  • 1. Iterate over the collection

    fun main(args: Array<String>){
    val items = list.of("java","kotlin","python")
    for(item in items){
    println(item)
    }
    }
  • 2. Use the in operator to determine whether a collection contains an instance

     when {
        "java" in items -> println("is good lang")
        "kotlin" in items -> println("is good good lang")
        else -> println("python is best lang")
    }
  • 3. Use lambda expressions to filter and map collections

    fun main(args: Array<String>){
     val langs = listOf("C","C++","Java","Python","JavaScript")
    
      langs
           .filter{ it.startsWith("C")}
           .sortedBy{ it }
           .map{ it.toUpperCase() }
           .forEach{ println(it) }
    }

11. Use loops

There are two ways of looping in Kotlin are for, while, using "in" in the for loop to traverse, and there are two traversal methods.

  • 1. For loop
  val items = listOf("java", "kotlin", "android")
    for (item in items) {//for遍历集合
        println("lang $item")
    }

    for (index in items.indices) {//类似于java中的数组的length-index的遍历
        println("The $index index is ${items[index]}")
    }
  • 2, while loop
    val items = listOf("java", "kotlin", "android")
    var index = 0
    while (index < items.size) {//while 循环的遍历方式
        println("The $index lang is ${items[index++]}")
    }

12. Use conditions if, when

The use of if in kotlin is similar to that in java, but in kotin if is an expression with a value, while in java it is a statement, you can use the if expression in kotlin to replace the ternary operator in java in kotlin. when is similar to switch function

fun main(args: Array<String>){

  println(descript("hello"))

}

fun descript(obj: Any): String = when(obj){

       1 -> "one"
       "hello" -> "hello word"
       is Long -> "long type"
       !is String -> "is not String"
       else -> {
            "unknown type"
       }


}

Thirteen, create classes and instances

 /**
  * Created by mikyou on 2017/11/9.
  */
fun main(args: Array<String>) {
    val rectangle = Rectangle(100.0, 200.0)
    val triangle = Triangle(100.0, 100.0, 100.0)
    println("rectangle is ${rectangle.isSquare}, and perimeter is ${rectangle.perimeter}, and area is ${rectangle.calculateArea()}")
    println("triangle  perimeter is ${triangle.perimeter}, and area is ${triangle.calculateArea()}")
}

abstract class Shape(val sides: List<Double>) {
    val perimeter: Double get() = sides.sum()
    abstract fun calculateArea(): Double
}

interface RectangleProperity {
    val isSquare: Boolean
}

class Rectangle(var height: Double, var length: Double)
    : Shape(listOf(height, length, height, length)), RectangleProperity {
    override fun calculateArea(): Double = height * length
    override val isSquare: Boolean get() = height == length
}

class Triangle(var sideA: Double, var sideB: Double, var sideC: Double)
    : Shape(listOf(sideA, sideB, sideC)) {
    override fun calculateArea(): Double = sideA * sideB * sideC
}

Guess you like

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