函数
函数定义
fun double(x: Int): Int {
return 2 * x
}
默认参数
fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size) {}
open class A {
open fun foo(i: Int = 10) {}
}
class B : A() {
override fun foo(i: Int) {//不允许子类覆盖默认参数
println(i)
}
}
//匿名函数
var niming = fun(x: Int): Int { return x + 8 }
//表达式函数
var sum2 = fun(a: Int, b: Int) = a + b//(Int,Int)->Int
//(Int,Int)->Int
fun sum3(age: Int, a: Int): Int {
return age + a
}
var dvi = fun(a: Int): Int {
return a
}//(Int) -> Int
//lambda表达式,其实和匿名函数一样
var sum = { arg1: Int, arg2: Int ->
println("lambda")
arg1 + arg2
}//(Int,Int)->Int
var plus = fun(): Int = 9//()->Int
fun println(strs: List<Int>) {
for (int in strs) {
println(int)
}
printUsage()
}//(List<Int>) -> Unit
fun getName(): String? {
return "hahah"
}//()->String?
object 表达式
// 匿名内部类
window.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
}
override fun mouseEntered(e: MouseEvent) {
}
})
还可以实现多个匿名内部类,Java是不可以的
open class A(x: Int) {
public open val y: Int = x
}
interface B {...}
val ab: A = object : A(1), B {
override val y = 15
}
声明单例
object DataProviderManager {
fun registerDataProvider(provider: DataProvider) {
}
val allDataProviders: Collection<DataProvider>
get() = // ...
}
看字节码,里面默认生成一个INSTENCE
半生对象:即:一个类全局只有这个对象,
class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
}
看字节码,Factory 里面的都是静态成员
学习Kotlin看官方文档很权威
网友评论