I have a sealed class that has different subtypes extending from it. When I try to use a when clause to filter out a subtype I keep getting unresolved reference "name"
sealed class Fruit(val name: String) {
object APPLE : Fruit(“apple”)
data class BANANA(val isFruit: Boolean) : Fruit(“banana”)
}
internal object Random {
fun build(name: String): FruitNinja{
when(name) {
Fruit.APPLE.name -> {
return AppleFruitNinja()
}
// keep getting error here Unresolved reference: name
Fruit.BANANA.name-> {
return BananaFruitNinja()
}
}
}
}
How can I use the "name" argument to filter in the when clause and build custom objects .
As correctly explained by @rajan.kali APPLE is an object and therefore you can access name directly. However, BANANA is a class so you need to create an instance of that class or I would suggest creating a companion object:
sealed class Fruit(val name: String) {
object APPLE : Fruit("apple")
data class BANANA(val isFruit: Boolean) : Fruit(name) {
companion object {
const val name = "banana"
}
}
}
and then you can use it in the same way as APPLE:
internal object Random {
fun build(name: String): FruitNinja {
when (name) {
Fruit.APPLE.name -> {
return AppleFruitNinja()
}
Fruit.BANANA.name -> {
return BananaFruitNinja()
}
}
}
}
As a last point, the build
method could be written in a more kotliny fashion:
internal object Random {
fun build(name: String): FruitNinja = when (name) {
Fruit.APPLE.name -> AppleFruitNinja()
Fruit.BANANA.name -> BananaFruitNinja()
else -> TODO()
}
}