[Programming Language] Kotlin Notes

basic grammar

variable

val (short for value) declares an immutable variable.

var (short for variable) declares a mutable variable.

Explicitly declare variable types:

val a: Int = 10

Correspondence between JAVA and Kotlin data types

JAVA Kotlin
int Int
long Long
short Short
float Float
double Double
boolean Boolean
char Char
byte Byte

function

fun 函数名(变量名:数据类型....:数据类型(返回值)
{
    
    
    
}

logical control statement

if statement can be used as return value

if(条件)
{
    
    
    
}
else
{
    
    
    
}
//精简写法
fun largerNumber(num1: Int, num2: Int) = if (num1 > num2) num1 else num2

when statement

fun getScore(name: String) = when (name) {
    
    
    "Tom" -> 86
    "Jim" -> 77
    "Jack" -> 95
    "Lily" -> 100
    else -> 0
}
匹配值 -> {
    
     执行逻辑 }
//类型匹配
fun checkNumber(num: Number) {
    
    
    when (num) {
    
    
        is Int -> println("number is Int")
        is Double -> println("number is Double")
        else -> println("number not support")
    }
}

while statement

while(执行条件)
{
    
    
    
}

for loop

for(i in collection)
{
    
    
    
}
//默认遍历步长为一,若修改遍历步长:
fun main() {
    
    
    for (i in 0 until 10 step 2) {
    
    
        println(i)
    }
}

downto keyword

//降序遍历
fun main() {
    
    
    for (i in 10 downTo 1) {
    
    
        println(i)
    }
}

kind

class 类名{
    
    }
//实例化
val p = 类名()
//继承
open class 类名{
    
    } //表示该类可以被继承
class Student:Person(){
    
    } 

primary constructor

  • It is the default no-argument construction and no function body. You can perform some operations on it through the init structure.
init
{
    
    
    println(".....")
}

secondary constructor

  • The secondary constructor is defined by the constructor keyword
class Student(val sno:String,val grade:Int,name:String,age:Int):Person(name,age)
{
    
    
    constructor(name:String,age:Int):this("",0,name,age){
    
     }
    constructor():this("",0){
    
    }
}

interface

//声明
interface Study
{
    
    
    fun readBooks()
    fun doHomework()
}
//实现
class Student(name:String,age:Int):Person(name,age),Study
{
    
    
    override fun readBooks() {
    
    
        println("ReadBook......")
    }

    override fun doHomework() {
    
    
        println("doHomework.....")
    }

}

data class

Add the data keyword in front of the data class to make the class a data class.

data class Cellphone(val brand:String,val price:Double)

The advantage of the data class is that kotlin will automatically generate fixed and meaningless methods such as equals, hashCode(), and toString() based on the parameters in the main constructor.

singleton class

public class Singleton {
    
    
    private static Singleton instance;

    private Singleton() {
    
    }

    public synchronized static Singleton getInstance() {
    
    
        if (instance == null) {
    
    
            instance = new Singleton();
        }
        return instance;
    }

    public void singletonTest() {
    
    
        System.out.println("singletonTest is called.");
    }
}

nullable type

class name + ? Such as: Int? String?

Auxiliary tool for empty judgment

  • Object?. The function object is not null to call the method normally, and if it is null, it does nothing.
  • ? : Return the result of the left expression if the result of the left expression is not empty, otherwise return the result of the right expression.
  • ! ! To force compilation, add !! after the object.

Lambda

A small piece of code that can be passed as a parameter.

Lambda expression structure

{
    
    参数名1:参数类型,参数名2:参数类型->函数体} //前面为参数列表
//对于单个与只有一个参数的Lambda表达式可以简写为
 	var a = listOf(1,2,3,4,5,6)
    a = a.map {
    
     it+1 }
    for (i in a)
    {
    
    
        print("\t"+i)
    }
//输出为:
	2	3	4	5	6	7

Collection creation and traversal

listOf creates an immutable collection and cannot call add or delete methods.

//创建
val list = listOf("Apple","Banana","Orange","Pear","Grape")
//遍历
 for (i in list)
 {
    
    
    println(i)
 }

Similar set collections can be created using setOf, or mutableSetOf() can be created through variable functions, and the above-mentioned creation is a mutable collection.

In particular, for Map, because the Map collection exists in the form of key-value pairs:

val map = mapOf("apple" to 1)

Aggregate function

maxByOrNull

val list = listOf("Apple", "Banana", "Orange", "Pear", "Grape", "Watermelon")
val maxLengthFruit = list.maxBy {
    
     it.length }
println("max length fruit is " + maxLengthFruit)

map, mapping function, specifying mapping rules in Lambda.

  val list = listOf("Apple", "Banana", "Orange", "Pear", "Grape", "Watermelon")
    val fruit = list.map {
    
     it.uppercase(Locale.getDefault()) }
    for (i in fruit)
    {
    
    
        println(i)
    }

filter , filter function, specify filter rules in Lambda.

   val list = listOf("Apple", "Banana", "Orange", "Pear", "Grape", "Watermelon")
    val fruit = list.filter {
    
     it.length<=4 }.map {
    
     it.uppercase(Locale.getDefault()) }
    for (i in fruit)
    {
    
    
        println(i)
    }

any and all,
if any satisfies the conditions, it returns true;
all satisfies the conditions and returns true

val list = listOf("Apple", "Banana", "Orange", "Pear", "Grape", "Watermelon")
    val anyResult = list.any{
    
     it.length<=5 }
    val allResult = list.all {
    
     it.length<=5 }
    println("anyResult is $anyResult, allResult is $allResult")

Guess you like

Origin blog.csdn.net/qq_51978873/article/details/124652113