matt tighe
06/17/2020, 9:37 PMsealed class ErrorStates {
object ThingsAreBadNow {
onAccess {
Logger.log("A bad thing happened")
}
}
}
The init
block can be used for data classes. Is there something I can do to get a similar behavior for objects?Casey Brooks
06/17/2020, 9:42 PMinit
can be used in any class, not just data classes. Just change object
to class
and have its usages create new instances instead of being a singletonmatt tighe
06/17/2020, 9:50 PMequals
and then hashMap
for a stateless class in a sealed class. adds a lot of unnecessary codeCasey Brooks
06/17/2020, 9:54 PMif (error == ThingsAreBadNow)
, do if (error is ThingsAreBadNow)
. No need to override equals/hashCode, and you get better type support with smart-casting or exhaustive when
expressionsmatt tighe
06/17/2020, 10:30 PMCasey Brooks
06/17/2020, 10:39 PMobject
for stateless subclasses since they will be always be the same, so you’d get fewer allocations. If you need to do something on accessing them, then it’s reasonable to want to create a new instance to trigger an init
block and ignore the warning. Although, doing any logic on object-creation is generally discouraged, and you might actually be best off just having a wrapper function to protect access to the object itself.
sealed class ErrorStates {
private object ThingsAreBadNow : ErrorStates()
companion object {
fun thingsAreBadNow() : ErrorStates {
Logger.log("A bad thing happened")
return ThingsAreBadNow
}
}
}