常用函数
let
Kotlin为了空安全不允许定义为空的,想要定义的话就必须加上问号。
1 | //可以为空 |
with
这个标准函数的作用是Lambda中的代码会持有对象的上下文,其最后一行代码为返回值。
1 | fun testWith(n: Int): String { |
run
这个标准函数的作用其实和 with 基本一致,只是使用方法上有所不同,with 需要括号中写入对象来进行操作,run 则是对象点进行操作。
1 | fun testRun(n: Int): String { |
apply
apply 使用方式和run一致,但是不同的是:最后一行不作为返回值。
1 | fun showDialog(activity: Activity) { |
关键字
lateinit
确定一定不为空可以使用 lateinit 这个关键字来定义全局变量。
1 | //不可以为空,不做初始化 |
如果需要判断是否初始化,可以使用isInitialized方法。
1 | fun testLet(){ |
sealed
密封类,少写一个else,其他特性还不知道呢。
1 | sealed class Result |
operator
运算符重载,可以对运算符进行重新自定义。
1 | operator fun String.times(n: Int): String { |
internal
限制不同 module 的访问,如果在 A module 中定义了一个 internal 方法,那么这个方法只能在 A module 中进行调用,在 B module 中是无法访问的。
inner
用来修饰内部类。
inline
内联函数,它的用法非常简单,只需要在高阶函数前加上 inline 关键字即可。
1 | inline fun high(block:(Int,Int) -> Int,block2:(Int,Int) -> Int){ |
noinline
指定参数为非内联函数。
1 | inline fun high(block:(Int,Int) -> Int,noinline block2:(Int,Int) -> Int){ |
infix
感觉用处不太大。
1 | infix fun String.begin(prefix:String):Boolean = startsWith(prefix) |
by
委托,可以为一些类创建委托类并重写或添加一些自己写的方法。
1 | class MySet<T>(val help:HashSet<T>) :Set<T> by help{ |
泛型
不多数,跟java类似。
1 | class Generic <T>{ |