文章目录

  • Android开发-Kotlin入门
  • 1.基础语法
  • 1.1 变量
  • 1.2 函数
  • 1.3 字符串模版
  • 1.4 条件表达式
  • 1.5 可空值及 *null* 检测
  • 1.6 *for* 循环
  • 1.7 *while* 循环
  • 1.8 *when* 表达式
  • 1.9 *range(in)* 区间
  • 1.10 集合
  • 1.11 类
  • 2 习惯用法
  • 2.1 创建 DTOs(POJOs/POCOs)
  • 2.2 类型判断
  • 2.3 遍历 map/pair型list
  • 2.4 区间
  • 2.5 *list*
  • 2.6 *map*
  • 2.7 延迟属性
  • 2.8 扩展函数
  • 2.9 创建单例
  • 2.10 缩写
  • 感谢


1.基础语法

1.1 变量

  • val

只读变量 val 定义。只能赋值一次

//sampleStart
val a: Int = 1 // 立即赋值
val b = 2 // 自动推断出 `Int` 类型
val c: Int // 如果没有初始值类型不能省略
c = 3 // 明确赋值
//sampleEnd

println("a = $a, b = $b, c = $c")
  • var

可重新赋值的变量使用 var 关键字

//sampleStart
var x = 5 // 自动推断出 `Int` 类型
x += 1
//sampleEnd

println("x = $x")
  • 过滤 list
val positives = list.filter { x -> x > 0 }
// 更短
val positives = list.filter { it > 0 }

1.2 函数

  • 两个 Int 参数、返回值 Int
//sampleStart
fun sum(a: Int, b: Int): Int {
    return a + b
}
//sampleEnd

fun main() {
    print("sum of 3 and 5 is ")
    println(sum(3, 5))
}
  • 表达式作为函数体、返回值类型自动推断
//sampleStart
fun sum(a: Int, b: Int) = a + b
//sampleEnd

fun main() {
    println("sum of 19 and 23 is ${sum(19, 23)}")
}
  • 返回无意义的值
//sampleStart
fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}
//sampleEnd

fun main() {
    printSum(-1, 8)
}

// 类型可省略
//sampleStart
fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}
//sampleEnd
  • 默认参数
fun foo(a: Int = 0, b: String = "") { …… }

1.3 字符串模版

fun main() {
    //sampleStart
    var a = 1
    // 模板中的简单名称:
    val s1 = "a is $a"
    
    a = 2
    // 模板中的任意表达式:
    val s2 = "${s1.replace("is", "was")}, but now is $a"
    //sampleEnd
    println(s2)
}

1.4 条件表达式

//sampleStart
fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}
//sampleEnd

fun main() {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}
  • 使用 if 作为表达式
//sampleStart
fun maxOf(a: Int, b: Int) = if (a > b) a else b
//sampleEnd

fun main() {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}

1.5 可空值及 null 检测

当某个变量的值可以为 null 的时候,必须在声明处的类型后添加 ? 来标识该引用可为
空。

如果 str 的内容不是数字返回 null

fun parseInt(str: String): Int? {
    // ……
}

使用返回可空值的函数

fun parseInt(str: String): Int? {
    return str.toIntOrNull()
}
//sampleStart
fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)
    // 直接使用 `x * y` 会导致编译错误,因为他们可能为 null
    if (x != null && y != null) {
        // 在空检测后,x 与 y 会自动转换为非空值(non-nullable)
        println(x * y)
    }
    else {
        println("either '$arg1' or '$arg2' is not a number")
    }
}
//sampleEnd

fun main() {
    printProduct("6", "7")
    printProduct("a", "7")
    printProduct("a", "b")
}

1.6 for 循环

fun main() {
    //sampleStart
    val items = listOf("apple", "banana", "kiwifruit")
    for (item in items) {
        println(item)
    }
    //sampleEnd
}

或者

fun main() {
    //sampleStart
    val items = listOf("apple", "banana", "kiwifruit")
    for (index in items.indices) {
        println("item at $index is ${items[index]}")
    }
    //sampleEnd
}

1.7 while 循环

fun main() {
    //sampleStart
    val items = listOf("apple", "banana", "kiwifruit")
    var index = 0
    while (index < items.size) {
        println("item at $index is ${items[index]}")
        index++
    }
    //sampleEnd
}

1.8 when 表达式

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

1.9 range(in) 区间

  • 区间内
fun main() {
    //sampleStart
    val x = 10
    val y = 9
    if (x in 1..y+1) {
        println("fits in range")
    }
    //sampleEnd
}
  • 区间外
fun main() {
    //sampleStart
    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")
    }
    //sampleEnd
}
  • 区间迭代
fun main() {
    //sampleStart
    for (x in 1..5) {
        print(x)
    }
    //sampleEnd
}
  • 数列迭代
fun main() {
    //sampleStart
    for (x in 1..10 step 2) {
        print(x)
    }
    println()
    for (x in 9 downTo 0 step 3) {
        print(x)
    }
    //sampleEnd
}

1.10 集合

val items1 = listOf("apple", "banana", "kiwifruit")
val items2 = setOf("apple", "banana", "kiwifruit")

/**
 *使用 lambda 表达式来过滤(filter)与映射(map)集合
 */
fun main() {
    //sampleStart
    val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
    fruits
        .filter { it.startsWith("a") }
        .sortedBy { it }
        .map { it.toUpperCase() }
        .forEach { println(it) }
    //sampleEnd
}

1.11 类

fun main() {
    //sampleStart
    val rectangle = Rectangle(5.0, 2.0) // 不需要“new”关键字
    val triangle = Triangle(3.0, 4.0, 5.0)
    //sampleEnd
    println("Area of rectangle is ${rectangle.calculateArea()}, its perimeter is ${rec
    tangle.perimeter}")
    println("Area of triangle is ${triangle.calculateArea()}, its perimeter is ${trian
    gle.perimeter}")
}
abstract class Shape(val sides: List<Double>) {
    val perimeter: Double get() = sides.sum()
    abstract fun calculateArea(): Double
}
interface RectangleProperties {
    val isSquare: Boolean
}
class Rectangle(
    var height: Double,
    var length: Double
) : Shape(listOf(height, length, height, length)), RectangleProperties {
    override val isSquare: Boolean get() = length == height
    override fun calculateArea(): Double = height * length
}
class Triangle(
    var sideA: Double,
    var sideB: Double,
    var sideC: Double
) : Shape(listOf(sideA, sideB, sideC)) {
    override fun calculateArea(): Double {
        val s = perimeter / 2
        return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC))
    }
}

2 习惯用法

2.1 创建 DTOs(POJOs/POCOs)

data class Customer(val name: String, val email: String)

会为 Customer 类提供以下功能:
**

  1. 所有属性的 getters (对于 var 定义的还有 setters)
  2. equals()
  3. hashCode()
  4. toString()
  5. copy()
  6. 所有属性的 component1() 、 component2() ……等等
    **

2.2 类型判断

when (x) {
    is Foo //-> ……
    is Bar //-> ……
    else //-> ……
}

2.3 遍历 map/pair型list

for ((k, v) in map) {
    println("$k -> $v")
}

kv 可以改成任意名字。

2.4 区间

for (i in 1..100) { …… } // 闭区间:包含 100
for (i in 1 until 100) { …… } // 半开区间:不包含 100
for (x in 2..10 step 2) { …… }
for (x in 10 downTo 1) { …… }
if (x in 1..10) { …… }

2.5 list

val list = listOf("a", "b", "c")

2.6 map

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

println(map["key"])
map["key"] = value

2.7 延迟属性

val p: String by lazy {
    // 计算该字符串
}

2.8 扩展函数

fun String.spaceToCamelCase() { …… }
"Convert this to camelcase".spaceToCamelCase()

2.9 创建单例

object Resource {
    val name = "Name"
}

2.10 缩写

  • If not null
val files = File("Test").listFiles()
println(files?.size)
  • If not null and else
val files = File("Test").listFiles()
println(files?.size ?: "empty")
  • if null 执行一个语句
val values = ……
val email = values["email"] ?: throw IllegalStateException("Email is missing!")
  • 在可能会空的集合中取第一元素
val emails = …… // 可能会是空集合
val mainEmail = emails.firstOrNull() ?: ""
  • if not null 执行代码
val value = ……
value?.let {
…… // 代码会执行到此处, 假如data不为null
}
  • 映射可空值(如果非空的话)
val value = ……
val mapped = value?.let { transformValue(it) } ?: defaultValueIfValueIsNull
  • 返回 when 表达式
fun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}
  • “try/catch”表达式
fun test() {
    val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }
    // 使用 result
}
  • “if”表达式
fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
    }
}
  • 返回类型为 Unit 的方法的 Builder 风格用法
fun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}
  • 单表达式函数
fun theAnswer() = 42

// 等价于
fun theAnswer(): Int {
    return 42
}

// 单表达式函数与其它惯用法一起使用能简化代码,例如和 when 表达式一起使用:
fun transform(color: String): Int = when (color) {
    "Red" -> 0
    "Green" -> 1
    "Blue" -> 2
    else -> throw IllegalArgumentException("Invalid color param value")
}
  • 对一个对象实例调用多个方法 ( with )
class Turtle {
    fun penDown()
    fun penUp()
    fun turn(degrees: Double)
    fun forward(pixels: Double)
}

val myTurtle = Turtle()
with(myTurtle) { // 画一个 100 像素的正方形
    penDown()
    for(i in 1..4) {
        forward(100.0)
        turn(90.0)
    }
    penUp()
}
  • Java 7 的 try with resources
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
    println(reader.readText())
}
  • 对于需要泛型信息的泛型函数的适宜形式
// public final class Gson {
// ……
// public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxExc
eption {
// ……
inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json,
T::class.java)
  • 使用可空布尔
val b: Boolean? = ……
if (b == true) {
    ……
} else {
    // `b` 是 false 或者 null
}
  • 交换两个变量
var a = 1
var b = 2
a = b.also { b = a }