[英]Best way to declare value in Kotlin class : in Constructor, body or init{}
[英]How to define a class with just one constructor with body in kotlin?
我想只用一個帶有body的構造函數來定義一個類。 當我設置類的參數時,我無法定義主構造函數的主體。 我希望該類只有一個構造函數。
敵人的例子
我有一個擴展CursorWrapper的類。 此類具有需要超類實現的參數。 我需要一個具有此功能的構造函數:
class wrapper(cursoe: Cursor): CursoreWrapper {
// i need to call super(cursor). But where?
}
如果要調用游標,則意味着您的CursorWrapper
(這里顯然是錯字)至少是一個抽象類,而不是一個接口。
從您的問題來看,它還會收到cursor
(另一個錯字)作為參數,因此我們得到如下信息:
open class CursorWrapper(cursor: Cursor)
現在,要調用此構造函數,只需在從類繼承時調用它即可:
class Wrapper(cursor: Cursor): CursorWrapper(cursor) // <- this is your super(cursor)
現在,我們假設您在構造CursorWrapper
需要調用另一個函數。
open class CursorWrapper(cursor: Cursor) {
fun bla() {
// You want to call this for some reason as super.bla()
}
}
您可以為此使用init()
塊。
class Wrapper(cursor: Cursor): CursorWrapper(cursor) {
// i need to call super(cursor). But where?
init {
super.bla()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.