I have this kind of implementation but it’s not al...
# random
s
I have this kind of implementation but it’s not allowed after bumping Kotlin to 1.6.10 and received the following error which was warning until previous version. Code:
Copy code
sealed class PowerTool(
    @JvmField open val name: String,
    @JvmField open val price: Double
) {
    data class CircularSaw(
        val diameter: Int,
        val cordless: Boolean,
        override val name: String,
        override val price: Double
    ) : PowerTool(name, price)

    data class DrillPress(
        val rpm: Int,
        override val name: String,
        override val price: Double
    ) : PowerTool(name, price)
}
Error: JvmField can only be applied to final property
My requirement for jvm field is: I need @JvmField for java consumers as I don’t want to refactor the code to use the setter/getter method and want to use as a field. Any thoughts?
b
Untitled.kt
l
You need to no longer make it open, which means removing the
data
modifier, and removing the `override val`s.
s
@louiscad: open i added so i can override them in the subclasses that was the purpose. and i don’t want to do the whole java refactor (for java consumers) so i have added jvm field. Are you suggesting to remove
data
modifier and remove
override val
and use a different name for it?
@Brett McGinnis: in the second solution, my java consumers won’t be happy and they need to refactor the code
e
overrideable
@JvmField
shouldn't have been allowed in the first place, it leads to broken code generation elsewhere in the compiler
I believe that louiscad is suggesting this
Copy code
sealed class PowerTool(
    @JvmField val name: String,
    @JvmField val price: Double
) {
    class CircularSaw(
        val diameter: Int,
        val cordless: Boolean,
        name: String,
        price: Double
    ) : PowerTool(name, price)

    class DrillPress(
        val rpm: Int,
        name: String,
        price: Double
    ) : PowerTool(name, price)
}
s
hmm, in this case i need to implement toString hashCode and all. would it work for
when
expression?
e
yes
l
The IDE can generate these
s
yes, IDE generate them but those are basic methods which are generated by IDE. I don’t think so that would work correctly. for eg: like this
Copy code
override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (javaClass != other?.javaClass) return false
            return true
        }

        override fun hashCode(): Int {
            return javaClass.hashCode()
        }