https://pl.kotl.in/WJxo0DujU(以下是鏈接中的代碼)
open class A() { }
class B(): A() {
fun pew2() { }
}
fun <a: A> a.pew() = apply { }
fun main() {
val b = B()
b.pew().pew2()
}
有沒有辦法讓pew()A 類中的函式(不在 A 的伴隨物件中)并且仍然能夠輸入b.pew().pew2()(不是b.apply { pew().pew2() })?
uj5u.com熱心網友回復:
您可以在其中創建pew()方法A并讓方法回傳實體本身:
open class A() {
fun pew() = this
}
class B(): A() {
fun pew2() { }
}
fun main() {
val b = (B().pew() as B).pew2()
}
uj5u.com熱心網友回復:
您可以覆寫 B 中的函式并縮小回傳型別。
open class A() {
open fun pew(): A {
//...
return this
}
}
class B: A() {
fun pew2() { }
override fun pew(): B {
super.pew()
return this
}
}
Kotlin 沒有一種self型別可以使這些型別的可鏈接函式更容易實作,但該apply函式使回傳相同物件的可鏈接函式變得不必要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/354356.html
標籤:科特林
