Kotlin Android

I used the auto-generator function for Android android for android studio, and he created the following code for me, but I can not understand why the final val for CREATOR needed? I see the final keyword for the first time in kotlin.

 data class Person( val name: String, val surname: String ) : Parcelable { constructor(source: Parcel): this(source.readString(), source.readString()) override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeString(name) dest?.writeString(surname) } companion object { @JvmField final val CREATOR: Parcelable.Creator<Person> = object : Parcelable.Creator<Person> { override fun createFromParcel(source: Parcel): Person { return Person(source) } override fun newArray(size: Int): Array<Person?> { return arrayOfNulls(size) } } } } 
+6
source share
2 answers

In Kotlin, classes and members are final by default . In other words, the following declarations have the same bytecode:

 @JvmField final val CREATOR: Parcelable.Creator<Person> = PersonCreator() @JvmField val CREATOR: Parcelable.Creator<Person> = PersonCreator() 

Thus, although the generated code has the final keyword, and this is not an error, it is redundant.

Although classes and members are final by default, there is still a need for a final modifier in Kotlin. One example would be to mark the open method as final in a derived class:

 open class Base { open fun test(){} } open class DerivedA : Base(){ final override fun test(){} } class DerivedB : DerivedA() { override fun test(){} //error: 'test' in 'DerivedA' is final and cannot be overriden } 

While it’s good practice to make the public static final field in java there is no strict requirement for the Parccelable.Creator field Parccelable.Creator marked as such:

Classes that implement the Parcelable interface must also have a non-empty static field called a type CREATOR that implements the Parcelable.Creator Interface.

+5
source

In Kotlin, you can simply use @Parcelize Kotlin Android Extension :

 @Parcelize data class User(val id: String, val name: String) : Parcelable 

This feature was experimental before Kotlin 1.3.40 . If you are still using a version of Kotlin earlier than 1.3.40, you need to enable experimental features in order to use this:

 android { // Enable @Parcelize // You only need this for Kotlin < 1.3.40 androidExtensions { experimental = true } ... } 
0
source

All Articles