class AttrDemo {
private var attr1: String = ""
protected var attr2: String = ""
// 默認 public
var attr3: String = ""
val roAttr: String = "readonly" // 僅 getter
// 自定義訪問器
var computed: String = ""
private set // setter 私有
get() = field.uppercase() // getter 轉大寫
}
String 必須在聲明或構造函數中初始化String? 可延遲初始化lateinit var 延遲初始化(非空、非基本類型),訪問前未初始化拋 UEEinterface MyInterface {
fun method1() // 抽象方法
fun method2() { } // 默認實現
val prop: Int // 抽象屬性(需實現類覆寫)
val constProp = 100 // 編譯期常量
}
class Impl : MyInterface {
override fun method1() { }
override val prop: Int = 10
}
override 抽象屬性class Box<T>(val value: T)
// 使用
val intBox = Box(1) // 類型推導 Box<Int>
val strBox: Box<String> = Box("hello")
// 協變:只讀生產者
interface Source<out T> { fun next(): T }
// 逆變:只寫消費者
interface Sink<in T> { fun put(value: T) }
// 星投影等價
List<*> ≡ List<out Any?>
inline fun <reified T> isInstance(value: Any): Boolean = value is T
// 運行時可訪問 T.class,無需傳 Class<T>
class Outer {
private val x = 1
class Nested { // 無外部類引用
fun foo() = 2 // 不能訪問 Outer.x
}
}
val n = Outer.Nested()
class Outer {
private val x = 1
inner class Inner { // 持有 Outer.this 引用
fun foo() = x // 可訪問外部私有字段
}
}
val i = Outer().Inner()
// 傳統匿名類
button.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) { }
})
// SAM 轉換:函數式接口單抽象方法
button.setOnClickListener { startActivity(Intent(this, MVPActivity::class.java)) }
enum class Direction { EAST, NORTH, SOUTH, WEST }
// 使用
val d = Direction.EAST
val d2 = Direction.valueOf("NORTH")
val all = Direction.values()
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}
// 訪問
val redHex = Color.RED.rgb.toString(16).uppercase() // "FF0000"
interface Describable { fun describe(): String }
enum class Status(val code: Int) : Describable {
SUCCESS(200) { override fun describe() = "成功" },
FAIL(500) { override fun describe() = "失敗" };
abstract fun describe(): String // 強制每個常量實現
}
GitHub:helloKotlin | 本站下載:源碼包