Parcelable Derived Class in Kotlin

2019-08-22 10:54发布

问题:

I'm using Android Parcelable plugin from https://github.com/nekocode/android-parcelable-intellij-plugin-kotlin

I tried it on a class with this definition

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>
}

and the definition was changed to

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>
}

Two syntax errors were highlighted.

In the line

class ChessClock() : TextView, Parcelable

TextView is underlined, with the comment "This type has a constructor, and must be initialized here."

In the line

constructor(context: Context) : super(context)

super is underlined, with the comment "Primary constructor call expected."

I've only been using kotlin for a few weeks, and I don't understand what's going on here. First of all, I know (or at least I think I know) that kotlin doesn't implement multiple inheritance, so I don't understand what

class ChessClock() : TextView, Parcelable

means. Is this really legitimate kotlin? How can one make a derived class Parcelable in kotlin?

回答1:

  1. TextView is a class and therefore your primary constructor should invoke one of its constructors
  2. you should invoke your primary constructor from other constructors

Example:

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)


回答2:

You could also just change the generated code from ChessClock() to ChessClock.