Class
主构造函数
init,可以有多个init,依次执行
class Constructor1 {
init {
// 初始化块 println("test")
}
}
次构造函数
constructor
次构造函数可以包含代码,调用次构造函数时必须要调用主构造函数,这一点非常重要
class Constructor4(str:String) {
init { // 初始化块
println("$str"+1)
}
init { // 初始化块
println("$str"+2)
}
constructor(str1: String, str2: String):this(str1) { // 调用主构造函数以及按照顺序调用多个初始化块
println("$str1 $str2")
}
init { // 初始化块
println("$str"+3)
}
fun foo() = println("this is foo function")
}
fun main(args: Array<String>) {
val obj = Constructor4("hello","world")
obj.foo()
}
// output
hello1
hello2
hello3
hello world
this is foo function
嵌套类 内部类
嵌套类:class 中的class,不能访问内部变量
内部类: 嵌套类前面加inner关键字,可访问内部变量
对象声明
对象声明是指在object
关键字之后指定对象名称。
Kotlin 通过对象声明可以实现单例模式,这是 Kotlin 在语法层面上的支持
伴生对象
Kotlin 没有static
关键字,在 Kotlin 类中也不能拥有静态属性和静态方法。使用伴生对象是解决这个问题的方法之一。
数据类
data class
协程
实现
launch 和 async
创建协程
在 Kotlin 中使用 launch 创建协程很简单,它会启动一个新的协程,返回一个 Job 对象。
fun main(args: Array<String>) {
val job = GlobalScope.launch {
delay(1000)
println("Hello Coroutines!")
}
Thread.sleep(2000)
}
async 跟 launch 的用法基本一致,使用 async 会返回一个 Deferred 对象。因此,async 创建的协程拥有返回值,通过 await() 方法将值返回。(如果要在线程中把值返回,直接使用 thread 会比较麻烦,可以考虑使用 Future。)
fun main(args: Array<String>) {
GlobalScope.launch {
val result1 = async {
delay(2000)
1
}
val result2 = async {
delay(1000)
2
}
val result = result1.await() + result2.await()
println(result)
}
Thread.sleep(5000)
}
// 3
Kotlin 的协程是依靠编译器实现的, 并不需要操作系统和硬件的支持。编译器为了让开发者编写代码更简单方便, 提供了一些关键字(例如suspend
), 并在内部自动生成了一些支持型的代码。
CoroutineContext
协程上下文,它包含了一个默认的协程调度器。所有协程都必须在 CoroutineContext 中执行。
CoroutineScope
协程作用域,它是一个接口只包含一个属性 coroutineContext。它定义了一个协程的作用范围。每个 Coroutine builder 都是 CoroutineScope 的扩展,CoroutineScope 会在具有生命周期的实体上实现。Kotlin 定义了一个全局的作用域 GlobalScope,用于启动顶级的协程,这些协程会在整个应用程序生命周期内运行。
CoroutineDispatcher
协程调度器,它用来调度和处理任务,决定了相关协程应该在哪个或哪些线程中执行。Kotlin 的协程包含了多种协程调度器。
suspend
协程可以被挂起而无需阻塞线程。我们使用suspend
关键字来修饰可以被挂起的函数。被标记为suspend
的函数只能运行在协程或者其他suspend
函数中。suspend
可以修饰普通函数、扩展函数和 lambda 表达式。
Job
任务执行的过程被封装成 Job,交给协程调度器处理。Job 是一种具有简单生命周期的可取消任务。当父类的 Job 被取消时,子类的 Job 也会被取消。 Job 拥有三种状态:isActive、isCompleted、isCancelled
Deferred
Deferred 是 Job 的子类。Job 完成时是没有返回值的,而 Deferred 在任务完成时能够
withContext
withContext的最后一行的值即为 withContext 的返回值
fun main(args: Array<String>) {
GlobalScope.launch {
val result1 = withContext(Dispatchers.Default) {
delay(2000)
1
}
val result2 = withContext(Dispatchers.IO) {
delay(1000)
2
}
val result = result1 + result2
println(result)
}
Thread.sleep(5000)
}
// 3