0

Need help with my example sealed class

sealed class Color
 object Red: Color()
 object Green: Color()
 object Blue: Color()

 class NewColor(
    var flag: Boolean = false,
    var id: String = "" or Int = -1 <-----I want id to be either an Int or String
): Color()

I'd like to be able to assign an Int or String to id. Do I need another sealed class?

So I can use it like

...
var result = NewColor(
        id = "Purple" or id = R.color.purple
    )
Android
  • 119
  • 9
  • Depends on your use case. You could also give the class a generic type that is used as the type of the ID. – Tenfour04 Sep 03 '20 at 03:39
  • 1
    Subclasses of a sealed class are not generally themselves marked sealed, and I can't see any reason for you to mark your `NewColor` class as sealed. I can't see how the notion of a sealed class has anything to do with your question about the `id` attribute of `NewColor`. If you want to be able to assign either a String or an Int to that attribute, then you should make it of type `Any`. I expect I might be missing the point of your question, but I can't reason as to what else you might be asking. – CryptoFool Sep 03 '20 at 04:22
  • I interpretted the question as asking if there should be two versions of `NewColor`, both subclasses of the sealed class. – Tenfour04 Sep 03 '20 at 15:21
  • @Steve sealed class ViewModelText { class ID(val id: Int) : ViewModelText() class Str(val raw: String) : ViewModelText() } – Android Sep 11 '20 at 03:10

0 Answers0