1

I have a sealed class declared as follows:

sealed class SealedClass {
  object Pizza: SealedClass()
  data class Hamburger(val hasCheese: Boolean): SealedClass()
}

I have a map that maps SealedClass keys to String values and I would like to retrieve a particular string whenever I access the SealedClass.Pizza key within the map, but the result of accessing the SealedClass.Pizza entry returns null when I attempt to use a SealedClass.Pizza key that I construct in a different segment of my code.

The SealedClass.Pizza objects produced seem to have different hashes, which would probably explain why this is the case. Printing them results in

SealedClass$Pizza@4cf4ae53 and SealedClass$Pizza@21773412

I was under the impression that objects were the same across all instances of a class, so I don't know why they have different hashes, but regardless, I would like to be able to use both of these SealedClass.Pizza objects to access the same string. How might I do this?

mooglin
  • 500
  • 5
  • 17
  • "SealedClass.Pizza key that I construct"...How can you construct an `object`? Something very weird is going on because Kotlin guarantees a single instance of any `object`. `object`s don't have constructors. – Tenfour04 Aug 25 '21 at 18:37
  • When I say construct I mean I just call Sealed Class.Pizza in multiple places throughout my code. I suppose this is just accessing that object – mooglin Aug 25 '21 at 18:48
  • Could you post a minimal example reproducing the issue? It's weird you're getting two instances of an `object` – gpunto Aug 25 '21 at 19:15
  • Also, can you clarify what you mean by “in a different segment of my code”?  (In particular, whether it's compiled at the same time, or if not, whether it's run in the same JVM.) – gidds Aug 25 '21 at 21:09

0 Answers0