// 类继承使用`:`声明
open class Shape // 该类开放继承
class TestClass(var height: Double, var length: Double): Shape() {
// 类声明中所列参数的默认构造函数会自动可用
var s = height * length
}
// 在 Kotlin 中的一个类可以有一个主构造函数以及一个或多个次构造函数。主构造函数是类头的一部分
class Person constructor(firstName: String) { /*……*/ }
class Person(firstName: String) { /*……*/ }
// 次构造函数
// 如果类有一个主构造函数or init(因为初始化代码块实际会成为主构造函数的一部分),每个次构造函数需要委托给主构造函数, 可以直接委托或者通过别的次构造函数间接委托。委托到同一个类的另一个构造函数用 this 关键字即可
class Person(val name: String) {
val children: MutableList<Person> = mutableListOf()
constructor(name: String, parent: Person) : this(name) {
parent.children.add(this)
}
}
// DetailActivity定义和使用伴生对象
class DetailActivity : AppCompatActivity() {
companion object {
const val LETTER = "letter"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
val letterId = intent?.extras?.getString(LETTER).toString()
// ...
// LetterAdapter使用
intent.putExtra(DetailActivity.LETTER, holder.button.text.toString()) // 传入一段数据
// Syntax for property delegation
var <property-name> : <property-type> by <delegate-class>()
var counter = 0 // 这个初始器直接为幕后字段赋值
set(value) {
if (value >= 0)
field = value
}
// Declare private mutable variable that can only be modified
// within the class it is declared.
private var _count = 0
// Declare another public immutable field and override its getter method.
// Return the private property's value in the getter method.
// When count is accessed, the get() function is called and
// the value of _count is returned.
val count: Int
get() = _count
// 检测是否已经初始化
if (foo::bar.isInitialized) {
println(foo.bar)
}
interface MyInterface {
val prop: Int // 抽象的
val propertyWithImplementation: String
get() = "foo"
fun foo() {
print(prop)
}
}
// 解决实现两个接口的冲突,A、B都有函数foo()
class D : A, B {
override fun foo() {
super<A>.foo()
super<B>.foo()
}
}
fun interface KRunnable {
fun invoke()
}
fun interface IntPredicate {
fun accept(i: Int): Boolean
}
// 创建一个类的实例
val isEven = object : IntPredicate {
override fun accept(i: Int): Boolean {
return i % 2 == 0
}
}
// 通过 lambda 表达式创建一个实例
val isEven = IntPredicate { it % 2 == 0 }
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // “this”对应该列表
this[index1] = this[index2]
this[index2] = tmp
} // MutableList<Int> 就是接收者
val list = mutableListOf(1, 2, 3)
list.swap(0, 2) // “swap()”内部的“this”会保存“list”的值
fun main() {
open class Shape
class Rectangle: Shape()
fun Shape.getName() = "Shape"
fun Rectangle.getName() = "Rectangle"
fun printClassName(s: Shape) {
println(s.getName())
}
printClassName(Rectangle())
// 打印'Shape',因为printClassName中接收的参数声明的是`Shape`类
}
fun main() {
class Example {
fun printFuncType() {
println("Class method")
}
}
fun Example.printFuncType() {
println("Extension func")
}
Example().printFuncType()
// print Class method
}
fun main() {
class Example {
fun printFuncType() {
println("Class method")
}
}
fun Example.printFuncType(i: Int) {
println("Extension func #$i")
}
Example().printFuncType(1)
// print Extension func #1
}
fun Any?.toString(): String {
if (this == null) return "null"
// 空检测之后,“this”会自动转换为非空类型,所以下面的 toString()
// 解析为 Any 类的成员函数
return toString()
}
val <T> List<T>.lastIndex: Int
get() = size - 1
val House.number = 1 // 错误:扩展属性不能有初始化器
class MyClass {
companion object { } // 将被称为 "Companion"
}
fun MyClass.Companion.printCompanion() { println("companion") }
fun main() {
MyClass.printCompanion()
}
package org.example.declarations
fun List<String>.getLongestString() { /*……*/}
package org.example.usage
import org.example.declarations.getLongestString
fun main() {
val list = listOf("red", "green", "blue")
list.getLongestString()
}
class Host(val hostname: String) {
fun printHostname() { print(hostname) }
}
class Connection(val host: Host, val port: Int) {
fun printPort() { print(port) }
fun Host.printConnectionString() {
printHostname() // 调用 Host.printHostname()
print(":")
printPort() // 调用 Connection.printPort()
}
fun connect() {
/*……*/
host.printConnectionString() // 调用扩展函数
}
}
fun main() {
Connection(Host("kotl.in"), 443).connect()
//Host("kotl.in").printConnectionString() // 错误,该扩展函数在 Connection 外不可用
}
fun main() {
val thread = Thread {
println("${Thread.currentThread()} has run")
}
thread.start()
}
import kotlinx.coroutines.*
// launch() 函数会根据括起来的代码(封装在可取消作业对象中)创建协程。launch() 用于无需在协程范围之外返回值的情况。
fun main() {
repeat(3) {
GlobalScope.launch {
println("Hi from ${Thread.currentThread()}")
}
}
}
import kotlinx.coroutines.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
val formatter = DateTimeFormatter.ISO_LOCAL_TIME
val time = { formatter.format(LocalDateTime.now()) }
suspend fun getValue() {}
fun main() {
runBlocking {
val num1 = getValue()
val num2 = getValue()
println("result of num1 + num2 is ${num1 + num2}")
}
}
clark.apply {
firstName = "Clark"
lastName = "James"
age = 18
}
// The equivalent code without apply scope function would look like the following.
clark.firstName = "Clark"
clark.lastName = "James"
clark.age = 18