枚举
示例代码
package com.leofight.kotlin3
enum class Season {
SPRING, SUMMER, AUTUMN, WINTER
}
enum class Season2(val temperature: Int) {
SPRING(10), SUMMER(30), AUTUMN(20), WINTER(-10)
}
//枚举中声明方法
enum class Season3 {
SPRING {
override fun getSession(): Season3 = SPRING
},
SUMMER {
override fun getSession(): Season3 = SUMMER
},
AUTUMN {
override fun getSession(): Season3 = AUTUMN
},
WINTER {
override fun getSession(): Season3 = WINTER
};
abstract fun getSession(): Season3
}
fun main(args: Array<String>) {
val seasons = Season.values()
//seasons.forEach { season: Season -> println(season) }
seasons.forEach { println(it) }
println("------------")
val season = Season.valueOf("SPRING")
println(season.name)
}
对象声明
示例代码
package com.leofight.kotlin3
import java.awt.event.WindowEvent
import java.awt.event.WindowListener
//对象声明
object MyObject {
fun method() = "hello world"
}
object MyObject2 : WindowListener {
override fun windowDeiconified(e: WindowEvent?) {
}
override fun windowClosing(e: WindowEvent?) {
}
override fun windowClosed(e: WindowEvent?) {
}
override fun windowActivated(e: WindowEvent?) {
}
override fun windowDeactivated(e: WindowEvent?) {
}
override fun windowOpened(e: WindowEvent?) {
}
override fun windowIconified(e: WindowEvent?) {
}
}
fun main(args: Array<String>) {
println(MyObject.method())
}
关于对象表达式与对象声明之间的区别
1.对象表达式是立刻初始化或者执行的
2.对象声明是延迟初始化的,在首次访问的时候进行
3.伴生对象是在其所对应的类被加载时初始化的,对应于Java的静态初始化
委托(delegation)
示例代码
package com.leofight.kotlin4
interface MyInterface {
fun myPrint()
}
class MyInterfaceImpl(val str: String) : MyInterface {
override fun myPrint() {
println("welcome " + str)
}
}
class MyClass(myInterface: MyInterface) : MyInterface by myInterface {
}
fun main(args: Array<String>) {
val myInterfaceImpl = MyInterfaceImpl("zhangsan")
val myClass = MyClass(myInterfaceImpl)
myClass.myPrint()
}
委托原理
by关键字后面的对象实际上会被存储在类的内部,编译器则会父接口中的所有方法实现出来,并且将实现转移给委托对象来去进行。