在Kotlin中,優化抽象類的結構可以通過以下方法實現:
interface CommonInterface {
fun commonMethod()
}
abstract class AbstractClass : CommonInterface {
abstract fun specificMethod()
}
abstract class AbstractClass {
abstract fun doSomething()
fun defaultDoSomething() {
// 默認實現
}
}
abstract class AbstractClass {
private var _property: String = ""
val property: String
get() = _property
set(value) {
_property = value
}
}
abstract class AbstractClass {
// ...
}
fun AbstractClass.extendedFunction() {
// 擴展函數實現
}
sealed class Shape {
data class Circle(val radius: Double) : Shape()
data class Rectangle(val width: Double, val height: Double) : Shape()
}
inline fun Shape.area(): Double {
return when (this) {
is Shape.Circle -> Math.PI * radius * radius
is Shape.Rectangle -> width * height
}
}
通過以上方法,可以有效地優化Kotlin抽象類的結構,提高代碼的可維護性和可擴展性。