【用 Kotlin 写 Android】基本语法概览

前言

本系列适用于有一定 Android 开发经验的开发者,如果你没有 Android 开发经验甚至没有 Java 开发经验,可能在学习本系列时会有一些概念没有仔细描述,请谅解。本系列默认你已经用 Android Studio 创建过 Kotlin Hello World 项目。

基础语法

这里罗列一些 Kotlin 的基础语法

包声明、引入包

package my.demo
import java.util.*

用 fun 声明函数

fun sum(a: Int, b: Int): Int {
    return a + b
}
// 推断返回值类型,函数体是表达式
fun sum(a: Int, b: Int) = a + b
// 返回值为空
fun printSum(a: Int, b: Int): Unit {
    println("do nothing")
}
// 返回值为空,省略 Unit(类似于 Void)
fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}

声明变量

// 变量值可变
var x = 5
x += 1
// 变量值不可变
val a: Int = 1
val b = 2
val c: Int
c = 3

注释

// This is an end-of-line comment
/* This is a block comment
   on multiple lines. */

字符模板

var a = 1
// 简单变量
val s1 = "a is $a"

a = 2
// 表达式
val s2 = "${s1.replace("is", "was")}, but now is $a"

条件判断

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

// 表达式判断
fun maxOf(a: Int, b: Int) = if (a > b) a else b

空值

// 最后面的问号代表返回值可能为空
fun parseInt(str: String): Int? {
    // ...
}

// 函数没有返回值
fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)
    if (x != null && y != null) {
        println(x * y)
        return
    } else {
        println("either '$arg1' or '$arg2' is not a number")
        return
    }
}

类型检查和自动转换

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // 判断出 obj 是字符串了,则自动转换成了字符串而不需要显示转换,obj 现在是字符串了
        return obj.length
    }
    // obj 仍然是 Any(Kotlin 中没有 Object,Any 类似于 Java 中的 Object)
    return null
}
// 上面的代码还可以这么写
fun getStringLength(obj: Any): Int? {
    if (obj !is String) return null
    // obj 自动换换成字符串
    return obj.length
}
fun getStringLength(obj: Any): Int? {
    // 在 && 后面的 obj 也可以自动转换
    if (obj is String && obj.length > 0) {
        return obj.length
    }
    return null
}

循环

// for 循环
val items = listOf("apple", "banana", "kiwifruit")
// 类似于伪代码,item 依次是 items 中的每一个
for (item in items) {
    println(item)
}
// items.indices 是 items 的下标索引,从 0 开始
for (index in items.indices) {
    println("item at $index is ${items[index]}")
}

// whilt 循环
var index = 0
while (index < items.size) {
    println("item at $index is ${items[index]}")
    index++
}

when 表达式

// when 类似于 Java 中的 switch-case
fun describe(obj: Any): String =
when (obj) {
    1          -> "One"
    "Hello"    -> "Greeting"
    is Long    -> "Long"
    !is String -> "Not a string"
    // else 是当其他条件都不满住的时候执行
    else       -> "Unknown"
}

范围表达式

val x = 10
val y = 9
if (x in 1..y+1) {
    println("fits in 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")
}

// 循环添加步长,每次增大或减小多少
for (x in 1..10 step 2) {
    print(x)
}
println()
for (x in 9 downTo 0 step 3) {
    print(x)
}

集合类

val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
    println(item)
}
// in 用于判断是否在集合内,类似于 Java 的 contain
when {
    "orange" in items -> println("juicy")
    "apple" in items -> println("apple is fine too")
}

val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
    // 过滤出 fruits 集合内所有以 a 开头的
    .filter { it.startsWith("a") }
    // 对过滤出的结果进行字典排序
    .sortedBy { it }
    // 对集合内每一个元素进行转换成大写的操作
    .map { it.toUpperCase() }
    // 对转换之后的值一次进行输出打印
    .forEach { println(it) }
// 为什么可以这么做,下一篇文章会详细介绍,这也是 Kotlin 中非常重要且核心的东西

类的创建

// Kotlin 没有 new 关键字,类名后加括号代表创建对象
val rectangle = Rectangle(5.0, 2.0)
val triangle = Triangle(3.0, 4.0, 5.0)

总结

以上这些是 Kotlin 的基本语法,其中还有很多东西不包括,包括类、继承、构造函数等,但那些东西不知 Kotlin 真正可 Java 区分出来的根本原因,Kotlin 更多建议的是函数式编程,当然,你不这样干也没有问题,但真正理解函数式编程的概念可能对你学习 Kotlin 大有好处。下一篇文章会深入了解一下上面这些基础语法,采用的方式是对学习 Kotlin 必做的项目 Kotlin Koans 进行讲解。


如果有一天你觉得过的舒服了,你就要小心了!欢迎关注我的公众号:我是任玉琢
qrcode_for_gh_45402a07f7d9_258

发布了79 篇原创文章 · 获赞 16 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/renyuzhuo0/article/details/79751585