funnum1AndNum2(num1:Int, num2:Int, operation: (Int, Int) ->Int): Int {
return operation(num1, num2)
}
funplus(num1:Int, num2:Int) : Int {
return num1 + num2
}
funminus(num1:Int, num2:Int) : Int {
return num1 - num2
}
fun StringBuilder.build(block:StringBuilder.() ->Unit) : StringBuilder {
block()
returnthis
}
val res1 = num1AndNum2(num1, num2, ::plus)
val res2 = num1AndNum2(num1, num2, ::minus)
val res3 = num1AndNum2(num1, num2) {n1, n2 ->
n1 + n2
}
11, vararg关键字对应java中的可变参数列表,允许传入0个,1个,2个,,,,,
12, by lazy 代码块懒加载
13, 类委托和委托属性
classMySet<T>(valhelperSet:HashSet<T>): Set<T> by helperSet {
overridefunisEmpty(): Boolean {
returnfalse
}
}
classMyClass {
var p by Delegate()
}
classDelegate {
var propValue:Any?=nulloperatorfungetValue(myClass:MyClass, prop:KProperty<*>): Any? {
return propValue
}
operatorfunsetValue(myClass:MyClass, prop:KProperty<*>, value:Any?) {
propValue = value
}
}
14, infix构建可读性函数
val list2 = listOf<String>("apple", "banana")
infixfun <T> Collection<T>.has(element:T) = contains(element)
if (list2 has "apple") {
println("list have apple")
}
15, 内联函数的泛型实化
inlinefun <reifiedT> getGenericType() =T::class.java
val res1 = getGenericType<String>()
16, 泛型的协变
classSimpleData<outT>(valdata:T?) {
funget(): T? {
return data
}
}