class ClassDemo // 無花括號也合法
直接在類頭聲明參數,配合 init 塊執行初始化邏輯:
class ClassDemo constructor(type: String) {
init { println("主構造函數參數: $type") }
var prop1 = type // 參數可直接用於屬性初始化
var prop2: String = type // 顯式類型聲明
}
類體內使用 constructor 關鍵字,必須委托主構造函數:
class ClassDemo(val type: String) {
constructor(type: String, extra: String) : this(type) {
println("次構造函數: $type $extra")
}
}
// 主構造函數參數加 var/val 直接成為屬性
class User(val name: String, var age: Int = 18)
// 等同於 Java
// private final String name;
// private int age;
// public User(String name, int age) { this.name=name; this.age=age; }
// public String getName() { return name; }
// public void setAge(int age) { this.age=age; }
public(無修飾符)private、protected、internal(模塊內可見)class Singleton private constructor()open class Base(val id: Int) // 必須 open 才能被繼承
class SubClass(id: Int, val name: String) : Base(id)
open,子類用 overrideopen,可加 final 禁止再次重寫super<Base>.method() 顯式指定open class Base { open fun foo() {} }
interface Ifc { fun foo() {} }
class Sub : Base(), Ifc {
final override fun foo() {
super<Base>.foo()
super<Ifc>.foo()
}
}
受限層級結構,子類固定且可攜帶狀態(枚舉增強版):
sealed class Expr {
data class Const(val number: Double) : Expr()
data class Sum(val left: Expr, val right: Expr) : Expr()
object NotANumber : Expr()
}
// when 表達式編譯器檢查窮盡性
fun eval(e: Expr): Double = when(e) {
is Expr.Const -> e.number
is Expr.Sum -> eval(e.left) + eval(e.right)
Expr.NotANumber -> Double.NaN
}
val user = User("Alice", 25)
val (name, age) = user // 解構聲明
println("$name is $age")
GitHub:helloKotlin | 本站下載:源碼包