Kotlin的可派生派生类
我使用Android Parcelable插件从https://github.com/nekocode/android-parcelable-intellij-plugin-kotlin
我用这个定义在一个类上试了一下
class ChessClock : TextView { lateinit var player:String constructor(context: Context) : super(context) constructor(context:Context, p:String, angle:Float) : this(context) { player = p rotation = angle } <snip> }
并将定义更改为
class ChessClock() : TextView, Parcelable { lateinit var player:String constructor(context: Context) : super(context) constructor(context:Context, p:String, angle:Float) : this(context){ player = p rotation = angle } <snip -- various stuff added here> }
突出显示了两个语法错误。
在线
class ChessClock() : TextView, Parcelable
TextView
加下划线,注释“这个类型有一个构造函数,并且必须在这里初始化”。
在线
constructor(context: Context) : super(context)
super
是强调的,并带有“预期的主要构造函数调用”的注释。
我只用了kotlin几个星期,我不明白这里发生了什么。 首先,我知道(或者至少我认为我知道)kotlin没有实现多重继承,所以我不明白
类ChessClock():TextView,Parcelable
手段。 这真的是合法的kotlin吗? 怎样才能在kotlin中创建派生类Parcelable?
- TextView是一个类,因此您的主要构造函数应该调用其构造函数之一
- 你应该从其他构造函数调用你的主构造函数
例:
class ChessClock(context: Context) : TextView(context), Parcelable //in this case you don't need other constructors but in-case you do, this is how you should write it: constructor(context: Context, dummy: Int): this(context)
您也可以将生成的代码从ChessClock()
更改为ChessClock
。