In theory, could `inline class` be used to make a ...
# announcements
r
In theory, could
inline class
be used to make a union type
g
Some limited implementation yes, why not, with single val with type Any and member functon like getYourTypeOrNull
e
can you illustrate with an example?
g
Who? Example of such inline class?
I mean something like:
Copy code
inline class FooOrBar(private val value: Any) {
    fun fooOrNull(): Foo? = value as? Foo
    fun barOrNull(): Bar? = value as? Bar
    fun isFoo() = value is Foo
    fun isBar() = value is Bar
}
Of course it doesn’t prevent from creating instance of this class in a wrong way, private constructors are not allowed for inline classes
it just sintactic sugar that helps you to use underlying value properly, but do not prevent from wrong state (when value is not foo and not bar) So if you want something more robust, use Sealed classes instead
e
thanks Andrey. Well you could also delegate the check to a Factory
g
You can delegate check to a Factory, you even don’t need check for that:
Copy code
fun Foo.toFooOrBar() = FooOrBar(this)
fun Bar.toFooOrBar() = FooOrBar(this)
fun Any.toFooOrBar() = if (this is Foo || this is Bar) FooOrBar(this) else error("Wrong type $this")
But it cannot guarantee you that someone from Java passed some other type or even from Kotlin didn’t use public constructor in a worng way, for example: FooOrBar(“some string)
But imho it’s fine. Confidence level is high enough to use this approach at least for your own code and have zero-cost union type wrapper with some nice helper functions that also easier too use than Any
You can even have generic version of such class
like: inline class Union2<A, B>(private val value: Any) { val first: A? = value as? A val first: B? = value as? B }
e
anyway, in that case I'm gonna have boxing, right?
g
No, if A and B are not primitive types
Yes, I saw this project
e
yeah sorry, I meant in case A and B were primitives
g
Of course, same will happen in case of common classes
you cannot have 2 primitive values in union class without box them to a class