关于android:Kotlin语言基础入门Kotlin简介

4次阅读

共计 4053 个字符,预计需要花费 11 分钟才能阅读完成。

在 2019 年 Google I/ O 大会上,Google 发表今后将优先采纳 Kotlin 进行 Android 开发。

一,简介

Kotlin 是一种富裕表现力且简洁的编程语言,不仅能够缩小常见代码谬误,还能够轻松集成到现有利用中。

Google 列举的 Kotlin 的劣势:

  • 富裕表现力且简洁:能够应用更少的代码实现更多的性能。表白本人的想法,少编写样板代码。
  • 更平安的代码:Kotlin 有许多语言性能,可帮忙你防止 null 指针异样等常见编程谬误。
  • 可互操作:能够在 Kotlin 代码中调用 Java 代码,或者在 Java 代码中调用 Kotlin 代码。Kotlin 可齐全与 Java 编程语言互操作。
  • 结构化并发:Kotlin 协程让异步代码像阻塞代码一样易于应用。协程可大幅简化后台任务治理。

更重要的是,Jetpack Compose 仅反对 Kotlin,而不再反对 Java。Google 提到多平台我的项目可应用 Kotlin 来开发。

二,概念介绍

1. 包的定义和应用

包的定义应该写在文件的顶部。

package com.rustfisher.ktpractice.intro

import kotlin.text.*

// ...

Kotlin 并不要求包名和文件寄存地位严格对应。

2. 程序入口

Kotlin 利用的程序入口是 main 办法。

fun main() {// ..}

另一个 main 办法带有参数

fun main(args: Array<String>) {// ...}

3. 规范输入

print办法将传入的变量打印到规范输出流。

print("Rust")
print("Fisher")

println打印传入变量并且在最初增加一个换行。

println("an.rustfisher.com")
println(42)

4. 办法

上面是一个承受 2 个 Int 参数,返回 Int 的办法。

fun sum(a: Int, b: Int): Int {return a + b}

办法主体能够是一个表达式。它的返回值能够被推断进去。

fun sum(a: Int, b: Int) = a + b

办法能够没有返回值,或者说是返回一个无意义的值(Unit)。

fun printSum(a: Int, b: Int): Unit {println("sum of $a and $b is ${a + b}")
}

Unit能够疏忽不写。

fun printSum(a: Int, b: Int) {println("sum of $a and $b is ${a + b}")
}

5. 变量

只能读的变量须要用关键字val。它们只能被赋值 1 次。

val a: Int = 1 // 间接赋值
val b = 2      // 主动揣测出是 Int 类型
val c: Int     // 当没有赋初始值时,须要申明类型 Type required when no initializer is provided
c = 3          // 这里是推延赋值

能够屡次赋值的变量用关键字var

var x = 5 // 主动揣测出是 Int 型
x += 1

能够在顶部申明变量

val PI = 3.14
var x = 0

fun incrementX() {x += 1}

6. 创立类与实例

定义一个类,应用 class 关键字

class Fisher

类的属性能够放在定义中或者类里。比方上面这个类Rectangle,形容长方形。

class Rectangle(var height: Double, var length: Double) {var perimeter = (height + length) * 2
}

默认结构器中的变量能够间接应用。这里能够间接应用面积变量perimeter

val rectangle = Rectangle(5.0, 2.0)
println("The perimeter is ${rectangle.perimeter}")

对于 kotlin v.1.4.30,类的继承用冒号 : 来示意。类默认都是 final 的,不可继承。为了继承,用 open 让这个类能被继承。

open class Shape
class Rectangle(var height: Double, var length: Double): Shape {var perimeter = (height + length) * 2
}

7. 正文

和其余古代编程语言相似,用 // 或者 /**/ 来正文

// 这里是正文 RustFisher
/**
 * 这是正文
 */
/* 这也是正文 */

8. 字符串模版(String tempplates)

间接应用变量,用$

要应用表达式,须要用大括号${}

var a = 1
// 简略应用 $
val s1 = "a is $a" 

a = 2
// 应用办法
val s2 = "${s1.replace("is","was")}, but now is $a"

9. 条件表达式

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

Kotlin 中,if也能够写成一个表达式

fun getMax(a: Int, b: Int) = if (a > b) a else b

10. for 循环

应用in

val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {println(item)
}

应用下标

val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {println("item at $index is ${items[index]}")
}
for (i in 1..3) {println(i)
}
for (i in 6 downTo 0 step 2) {println(i)
}

11. while 循环

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

12. when 表达式

when看起来有点像 Java 里的witch,但这两个是不同的货色。

fun describe(obj: Any): String =
    when (obj) {
        1          -> "One" 
        "Hello"    -> "Greeting"
        is Long    -> "Long"
        !is String -> "Not a string"
        else       -> "Unknown"
    }

13. 范畴

查看一个数字是否在范畴中,应用 in 操作

val x = 10
val y = 9
if (x in 1..y+1) {println("在范畴内")
}

查看一个数是否超出了范畴

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

if (-1 !in 0..list.lastIndex) {println("-1 超出了范畴")
}
if (list.size !in list.indices) {println("list 的 size 也超出了下标范畴")
}

遍历一个范畴

for (x in 1..5) {print(x)
}

指定步进值

for (x in 1..10 step 2) {print(x)
}
println()
for (x in 9 downTo 0 step 3) {print(x)
}

14. 汇合

遍历一个汇合

for (item in items) {println(item)
}

查看汇合中是否蕴含某个对象,用 in 操作

when {"orange" in items -> println("juicy")
    "apple" in items -> println("apple is fine too")
}

用 lambda 表达式对汇合进行 filter 和 map 操作

val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
    .filter {it.startsWith("a") }
    .sortedBy {it}
    .map {it.toUpperCase() }
    .forEach {println(it) }

15. 可为 null 的值和 null 查看

能够为 null 的变量,前面须要一个问号?

上面这个办法返回 Int 或者 null

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

应用可能返回 null 的办法(下面那个办法)

fun printProduct(arg1: String, arg2: String) {val x = parseInt(arg1)
    val y = parseInt(arg2)

    // Using `x * y` yields error because they may hold nulls.
    if (x != null && y != null) {
        // x 和 y 通过 null 检测后主动变成了非 null 值
        println(x * y)
    }
    else {println("'$arg1' or '$arg2' 不是数字 ")
    }    
}

或者写做

// ...
if (x == null) {println("参数谬误 arg1:'$arg1'")
    return
}
if (y == null) {println("参数谬误 arg2:'$arg2'")
    return
}

// x 和 y 通过 null 检测后主动变成了非 null 值
println(x * y)

16. 类型检查和主动转换

is 来查看某个对象是不是某个类型。如果确定某个不可变的变量的类型,那前面应用它的时候不必再显式转换

fun getStringLength(obj: Any): Int? {if (obj is String) {
        // obj 曾经主动转换为 String 类型
        return obj.length
    }

    // 这里的 obj 依然是 Any 类型
    return null
}

或者用!is

fun getStringLength(obj: Any): Int? {if (obj !is String) return null

    // 这里的 obj 曾经主动转换为 String 类型
    return obj.length
}

再换个写法

fun getStringLength(obj: Any): Int? {
    // 这外面的 obj 曾经主动转换为 String 类型
    if (obj is String && obj.length > 0) {return obj.length}

    return null
}

文末分享:140 集 Kotlin 入门到精通全系列(我的项目开发实战)视频教程

正文完
 0