Hello,
I have a sealed class that represents a value container for either string, boolean, int or double.
the subtypes hold one of each values respectively. I have an abstract method that returns the value contained. The problem is that the value held as field is resolved in the get method: is there a fix?
sealed class ValueContainer<T>(value:T) {
abstract fun get(): T
class Int_value(value: Int):ValueContainer<Int>(value){
override fun get():Int{
// this gives an unresolved reference error, is there a fix?
return value
}
}
...
}
The problem here is that neither of the value parameters is persisted: they’re simply parameters passed to the relevant constructor, and discarded when it has finished.
Instead, I think you want to store the value as a property of the class — which is as simple as inserting val * before the very first value. That tells Kotlin to create a property of the same name as the param, and initialise it from the param. You can then refer to it in methods of that class, such as get().
(However, if your class isn’t going to do significantly more than in your example, then you may be doing a lot of unnecessary work! First, there’s probably no point in having the get() method at all, since other code can simply refer to value directly*. And secondly, there may not be much point in having the subclass, since it seems to have no benefit over using ValueContainer<Int> directly. Both changes would reduce the whole class to a one-liner…)
(If you don’t want the property to be public, use private val instead.)
sealed interface ValueContainer<T : Any> {
val value: T
data class StringContainer(override val value: String) : ValueContainer<String>
data class BooleanContainer(override val value: Boolean) : ValueContainer<Boolean>
data class IntContainer(override val value: Int) : ValueContainer<Int>
data class DoubleContainer(override val value: Double) : ValueContainer<Double>
}