eygraber
06/05/2023, 4:18 AMLoney Chou
06/05/2023, 5:18 AMenum class Type<T> {
INT<Int>,
LONG<Long>,
FLOAT<Float>,
DOUBLE<Double>
}
This is cursed.eygraber
06/05/2023, 6:03 AMA
, a Delegate
interface that describes the actions that need to be taken for each subclass in A
, and a Delegates
enum that provides the actual implementation of the actions for each subclass of A
.
The original issue is that provide
is "static", almost like an A factory. This pattern works fine for that. But once I started doing that, I enjoyed moving the logic from companion objects in A subclasses (or from the subclass itself if it was an object
) to Delegates
because it made A much more clean.
I wanted to do the same for toUri
but that works by creating a Uri
to represent the A
subclass, i.e. it operates on an instance of A
. So I need Delegate
to be typed to specific subclasses of `A`:
interface Delegate<T> {
fun Uri.provide(): T?
fun toUri(t: T): String
}
sealed interface A {
fun toUri(): String
object B : A {
override fun toUri() = ADelegates.B.toUri(this)
}
object C : A {
override fun toUri() = ADelegates.C.toUri(this)
}
}
enum class ADelegates<T : A> : Delegate<T> {
B<A.B> {
override fun Uri.provide() = ...
override fun toUri(t: A.B) = "..."
},
C<A.C> {
override fun Uri.provide() = ...
override fun toUri(t: A.C) = "..."
}
}
Youssef Shoaib [MOD]
06/05/2023, 10:37 AMeygraber
06/05/2023, 12:12 PMspand
06/05/2023, 12:36 PM.sealedSubclasses
) but unfortunately not in a way to provide exhaustive checks. Its a shame enums are still superior in this regard.eygraber
06/05/2023, 12:39 PMsealedSubclasses
uses reflection which I don't want to useYoussef Shoaib [MOD]
06/05/2023, 2:10 PM.values
and other nice extensions for your sealed class (as long as all its non-sealed inheritors are objects). It can even generate an enum based on your sealed class. You can absolutely with sealed classes get exhaustive checks btw.ephemient
06/05/2023, 2:20 PMeygraber
06/05/2023, 2:26 PMhttps://github.com/livefront/sealed-enum
Looks cool, I'll check it out
you can absolutely with sealed classes get exhaustive checks
I never claimed otherwise; by enumerate I meant there's no way to iterate over then like enum values
https://youtrack.jetbrains.com/issue/KT-25871/Provide-ability-to-enumerate-all-direct-subclasses-of-a-sealed-class-at-compile-time-without-reflection
Linked above 😁
reflekt
I looked at that originally but the README says that it supports Kotlin 1.7 and I'm on 1.8
Hanno
06/05/2023, 6:31 PMeygraber
06/05/2023, 6:33 PMHanno
06/05/2023, 7:18 PMeygraber
06/05/2023, 7:56 PM