Monday, November 4, 2019

Kotlin basic syntax

Kotlin files are suffixed with .kt.

Package statement

The beginning of the code file is generally the declaration of the package:
package com.tienanhvn.main
import java.util.*
fun test() {}
class Tienanhvn {}
The kotlin source files do not need to match the directories and packages, and the source files can be placed in any file directory.

In the above example, the full name of test() is com.runoob.main.test, and the full name of Tienanhvn is com.tienanhvn.main.Tienanhvn.

If no package is specified, the default is the default package.
Kotlin basic syntax


Default import

Multiple packages are imported into each Kotlin file by default:

Kotlin.*
Kotlin.annotation.*
Kotlin.collections.*
Kotlin.comparisons.*
Kotlin.io.*
Kotlin.ranges.*
Kotlin.sequences.*
Kotlin.text.*
 Function definition
The function definition uses the keyword fun, and the parameter format is: parameter : type
fun sum(a: Int, b: Int): Int { 
    return a + b
}
The expression is a function body, and the return type is automatically inferred:
fun sum(a: Int, b: Int) = a + b
public fun sum(a: Int, b: Int): Int = a + b 
A function with no return value (similar to void in Java):
fun printSum(a: Int, b: Int): Unit {
    print(a + b)
}
public fun printSum(a: Int, b: Int) {
    print(a + b)

Variable length parameter function

The variable length parameter of a function can be identified by the vararg keyword:
fun vars(vararg v:Int){
    for(vt in v){
        print(vt)
    }
}
fun main(args: Array<String>) {
    vars(1,2,3,4,5)  // 输出12345
}

Lambda (anonymous function)
An example of a lambda expression:
fun main(args: Array<String>) {
    val sumLambda: (Int, Int) -> Int = {x,y -> x+y}
    println(sumLambda(1,2)) 
Defining constants and variables
Variable variable definition: var keyword
Var <identifier> : <type> = <initialization value> 
Immutable variable definition: val keyword, a variable that can only be assigned once (similar to the variable modified in Java).
Val <identifier> : <type> = <initialization value> 
Constants and variables can have no initialization value, but must be initialized before reference

The compiler supports automatic type judging, that is, the type can be specified without being specified by the compiler.
val a: Int = 1
val b = 1     
val c: Int   
c = 1         

var x = 5       
x += 1 
Comment
Kotlin supports single-line and multi-line comments, examples are as follows:
// This is a one-line comment
/* This is a multi-line
    Block comment. */ 
Unlike Java, block comments in Kotlin allow nesting.

String template
$ represents a variable name or variable value

$varName represents the value of the variable

${varName.fun()} represents the method return value of the variable:
var a = 1
val s1 = "a is $a"
a = 2
val s2 = "${s1.replace("is", "was")}, but now is $a" 
NULL check mechanism
Kotlin's empty security design is for nullable parameters. When using it, it needs to be judged empty. There are two ways to deal with it. After the field is added!! Throw an empty exception like Java, and add another field. Do not do it. Processing return value is null or match?: Short judgment processing
var age: String? = "23"
val ages = age!!.toInt()
val ages1 = age?.toInt()
val ages2 = age?.toInt() ?: -1
When a reference may be a null value, the corresponding type declaration must be explicitly marked as nullable.
Returns null when the string content in str is not an integer:
fun parseInt(str: String): Int? {
  // ...
}
The following example demonstrates how to use a function whose return value can be null:
fun main(args: Array<String>) {
  if (args.size < 2) {
    print("Two integers expected")
    return
  }
  val x = parseInt(args[0])
  val y = parseInt(args[1])
 
  if (x != null && y != null) {
    print(x * y)
  }
Type detection and automatic type conversion
We can use the is operator to detect if an expression is an instance of a type (similar to the instanceof keyword in Java).
fun getStringLength(obj: Any): Int? {
  if (obj is String) {
 
    return obj.length
  }
  // if (obj !is String){
  //   // XXX
  // }
  return null
}
 fun getStringLength(obj: Any): Int? {
  if (obj !is String)
    return null

  return obj.length
}
fun getStringLength(obj: Any): Int? {
 
  if (obj is String && obj.length > 0)
    return obj.length
  return null
Interval
The interval expression is formed by the rangeTo function with the operator form .. with in and !in.

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

No comments:

Post a Comment