Joan Colmenero
03/23/2020, 3:31 PMsealed class
to use it as a parent?
sealed class ClientName {
data class normalClass(val name: String) : ClientName()
object SpecificObject : ClientName()
object AnotherObject : ClientName()
}
So now, I need to have the same objects and class but different output, so on my extension function :
That is something like this :
fun ClientName.toText(): String = when (this) {
is ClientName.SpecificObject -> "Print1"
is ClientName.AnotherObject -> "Print2"
is ClientName.normalClass -> if (this.name == "") "hello" else "Bye"
}
So now I see that I'd need different types, it means that SpecificObject
, AnotherObject
and normalClass
are goinna print different things depends of the type, so what I thought is create another sealed class
like :
sealed class Type1 : ClientName()
sealed class Type2 : ClientName()
And then in that extension toText
check if is Type1
then do X and if it's Type2
do Y.
But I do not know how to do it to get the same values and same clases as the ClientName
what I'm missing?streetsofboston
03/23/2020, 3:38 PMsealed class ClientName {
data class normalClass(val name: String) : ClientName()
object SpecificObject : ClientName()
object AnotherObject : ClientName()
}
sealed class Type1 : ClientName()
sealed class Type2 : ClientName()
Then
fun ClientName.toText(): String = when (this) {
is ClientName.SpecificObject -> "Print1"
is ClientName.AnotherObject -> "Print2"
is ClientName.normalClass -> if (this.name == "") "hello" else "Bye"
is Type1 -> { X }
is Type2 -> { Y }
}
Joan Colmenero
03/23/2020, 3:40 PMType1.SpecificObject
Joan Colmenero
03/23/2020, 3:43 PMUnresolved reference SpecificObject
streetsofboston
03/23/2020, 3:43 PMClientName.SpecificObject
.
I think you may need to rethink your sealed class hierarchystreetsofboston
03/23/2020, 3:44 PMSpecificObject
in Type1
… it is a (static/global) singleton.Joan Colmenero
03/23/2020, 3:46 PMClientName
... but I do not know if it's good to do thatJoan Colmenero
03/23/2020, 3:47 PMClientName
tseisel
03/23/2020, 3:49 PMabstract fun
in the sealed class (i.e., use polymorphism):
sealed class ClientName {
abstract fun toText(): String
data class NormalClass(val name: String) : ClientName() {
override fun toText(): String = if (name.isEmpty()) "hello" else "Bye"
}
object SpecificObject : ClientName() {
override fun toText(): String = "Print1"
}
}
Joan Colmenero
03/23/2020, 5:13 PMstreetsofboston
03/23/2020, 5:14 PMJoan Colmenero
03/23/2020, 5:15 PMsealed class ClientName {
data class normalClass(val name: String) : ClientName()
object SpecificObject : ClientName()
object AnotherObject : ClientName()
}
sealed class Type1 : ClientName()
sealed class Type2 : ClientName()
But then I have to put the data class normalClass..
inside of each typeJoan Colmenero
03/23/2020, 5:15 PMstreetsofboston
03/23/2020, 5:17 PM