Kotlin快速教学

本教材依托于官方文档,着重写于java不同的地方

入门

函数

fun main()
{
    println("Hello wolrd!")
}

数据类型

普通变量

var a=Int=1var a=1,定义的类型均为对象

常量

val a = 1,后续其值不可更改

String常用操作

val string:String="123"

//java没有的特性
println(string[0])
println(string == "321")

//子串内插入
val a = 1
println("Str${a + 1}ing") //Str1ing

分类

类别 基本类型
Interger Byte,Short,Int,Long
Unsigned UByte … and so on
Floating Float,Double
Booleans Boolean
Characters Char
Strings String

数据结构

List

分为只读和可变list

// Read only list
val readOnlyShapes = listOf("triangle", "square", "circle")
println(readOnlyShapes)
// [triangle, square, circle]

// Mutable list with explicit type declaration
val shapes: MutableList<String> = mutableListOf("triangle", "square", "circle")
println(shapes)
// [triangle, square, circle]

casting操作

val shapes: MutableList<String> = mutableListOf("triangle",     "square", "circle")
val shapesLocked: List<String> = shapes

访问方式和数据一致,使用index访问
可使用add()remove()方法添加和删除元素

Set

只读和可变Set

// Read-only set
val readOnlyFruit = setOf("apple", "banana", "cherry", "cherry")
// Mutable set with explicit type declaration
val fruit: MutableSet<String> = mutableSetOf("apple", "banana", "cherry", "cherry")

println(readOnlyFruit)
// [apple, banana, cherry]

判断是否在set中,使用in

val readOnlyFruit = setOf("apple", "banana", "cherry", "cherry")
println("banana" in readOnlyFruit)
// true

Map

使用to完成key-value的映射

// Read-only map
val readOnlyJuiceMenu = mapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
println(readOnlyJuiceMenu)
// {apple=100, kiwi=190, orange=100}

// Mutable map with explicit type declaration
val juiceMenu: MutableMap<String, Int> = mutableMapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
println(juiceMenu)
// {apple=100, kiwi=190, orange=100}

Control Flow

When

val obj = "Hello"

when (obj) {
    // Checks whether obj equals to "1"
    "1" -> println("One")
    // Checks whether obj equals to "Hello"
    "Hello" -> println("Greeting")
    // Default statement
    else -> println("Unknown")     
}
// Greeting

或者赋值类型的


val obj = "Hello"    

val result = when (obj) {
    // If obj equals "1", sets result to "one"
    "1" -> "One"
    // If obj equals "Hello", sets result to "Greeting"
    "Hello" -> "Greeting"
    // Sets result to "Unknown" if no previous condition is satisfied
    else -> "Unknown"
}
println(result)
// Greeting

还可以使用when来完成布尔类型的判断

val temp = 18

val description = when {
    // If temp < 0 is true, sets description to "very cold"
    temp < 0 -> "very cold"
    // If temp < 10 is true, sets description to "a bit cold"
    temp < 10 -> "a bit cold"
    // If temp < 20 is true, sets description to "warm"
    temp < 20 -> "warm"
    // Sets description to "hot" if no previous condition is satisfied
    else -> "hot"             
}
println(description)
// warm

Loops

..表示前后都包含,比如1..4表示1, 2, 3, 4
..<表示不包含最后一个,比如1..<4表示1, 2, 3
downTo表示逆序,比如4 downTo 1表示4, 3, 2, 1
step表示步幅,比如1..5 step 2表示1, 3, 5

对于Char类型变量也适用,比如'z' downTo 's' step 2表示'z', 'x', 'v', 't'

那么对于循环,基于上述的range表示方法就很容易写出来

for(number in 1..5){}

for(cake in cakes){}

Functions

fun sum(x: Int, y: Int): Int {
    return x + y
}

fun main() {
    println(sum(1, 2))
    // 3
}

简写,去掉{}

fun sum(x: Int, y: Int) = x + y

fun main() {
    println(sum(1, 2))
    // 3
}

Lambda

fun main() {
    println({ string: String -> string.uppercase() }("hello"))
    // HELLO
}

可以将lambda表达式设为一个变量,比如

fun main() {
    val upperCaseString = { string: String -> string.uppercase() }
    println(upperCaseString("hello"))
    // HELLO
}

或者使用filter()来过滤

val numbers = listOf(1, -2, 3, -4, 5, -6)
val positives = numbers.filter { x -> x > 0 }
val negatives = numbers.filter { x -> x < 0 }
println(positives)
// [1, 3, 5]
println(negatives)
// [-2, -4, -6]

使用map()完成映射

val numbers = listOf(1, -2, 3, -4, 5, -6)
val doubled = numbers.map { x -> x * 2 }
val tripled = numbers.map { x -> x * 3 }
println(doubled)
// [2, -4, 6, -8, 10, -12]
println(tripled)
// [3, -6, 9, -12, 15, -18]

Kotlin快速教学
https://dreamerland.cn/2024/03/04/Kotlin1/
作者
Silva31
发布于
2024年3月4日
许可协议