I find myself wishing for a `union` type - I know ...
# getting-started
v
I find myself wishing for a
union
type - I know it's not coming. Can anyone think of a less verbose way of implementing these combination of sealed classes?
Copy code
val modifiers: MutableMap<String,Attribute> = mutableMapOf()
sealed class Attribute {
	data class fValue(val value: Float) : Attribute() {
		override fun toString(): String {
			return value.toString()
		}
	}
	data class iValue(val value: Int): Attribute()	{
		override fun toString(): String {
			return value.toString()
		}
	}
	data class sValue(val value: String): Attribute() {
		override fun toString(): String {
			return value.toString()
		}
	}
	data class bValue(val value: Boolean): Attribute() {
		override fun toString(): String {
			return value.toString()
		}
	}
	data class lValue(val value: Long) : Attribute() {
		override fun toString(): String {
			return value.toString()
		}
	}
}
k
Untitled
it does seem that this will cause boxing for
getValue()
which might be a bug?
v
I've been avoiding
Any
because these will all be serialized to json.
k
Using kotlin serialization or something else?
v
Yes, kotlinx serialization.
m
data class
defines its own
toString()
which clobbers the one in
Attribute
. Here is my take:
Copy code
sealed class Attribute<T>(open val value: T) {
	override fun toString() = value.toString()

	class fValue(override val value: Float) : Attribute<Float>(value)

	class iValue(override val value: Int): Attribute<Int>(value)

	class sValue(override val value: String): Attribute<String>(value)

	class bValue(override val value: Boolean): Attribute<Boolean>(value)

	class lValue(override val value: Long) : Attribute<Long>(value)
}
k
oh true, but you can make toString final in Attribute
and i think we are still causing unnesesairy boxing
m
another option is to skip the sealed class and use a private constructor to control what types are valid:
Copy code
class Attribute<T> private constructor(val value: T) {
	override fun toString() = value.toString()
  
  companion object {
    fun of(value: Float) = Attribute(value)
    fun of(value: Int) = Attribute(value)
    fun of(value: String) = Attribute(value)
    fun of(value: Boolean) = Attribute(value)
    fun of(value: Long) = Attribute(value)
  }
}
👍 2