Hi all, Is there such a thing as union types in Ko...
# getting-started
g
Hi all, Is there such a thing as union types in Kotlin? I looked in the Kotlin in Action book and haven't find such thing. That is, I would like to define my a property like this:
class MyClass(val myProperty: Boolean|MyType)
. The type of
myProperty
is a union of
Boolean
and
MyType
types. That is,
myProperty
value can be one of those types.
c
There are no union types. What are you trying to do exactly? There are always other ways to model this.
g
I would like to allow user to provide a way to enable/configure a feature either in a simplified or full form. That is, user can provide:
some_feature: true
if they want to enable that feature with default parameters, or
my_feature: { prop1: value1}
if they want to enable the feature and provide feature configuration.
I was thinking to model this as:
class Settings(val feature: Boolean|FeatureConfig)
t
You could just have two constructors, one for default value and the other with specifics
Copy code
class MyClass(
    val flag1: Boolean,
    val flag2: Boolean,
    val flag3: String,
) {
    constructor() : this(flag1 = false, flag2 = false, flag3 = "")
}

MyClass() or MyClass(flag1 = true, flag2 = false, flag3 = "test")
or simply just have the default values filled in, and the user can customize just the ones they want:
Copy code
class MyClass(
    val flag1: Boolean = false,
    val flag2: Boolean = false,
    val flag3: String = "",
)

MyClass() or MyClass(flag2 = true)
c
Copy code
class MyClass(
    val myProperty: MyType,
) {
    constructor(myProperty: Boolean) : this(MyType(myProperty))
}
The key is: do you care that the user specified a boolean? Most likely, no. The boolean is here for convenience during creation, but after that it's pointless. You probably don't want to write
if (myProperty is Boolean) … else if (myProperty is MyType)
each time you want to use the property. Thus, the boolean should only appear in the constructor, and after that the property is the type.
g
right
c
This constructor overload is a great choice when only one of these arguments is required, but it doesn't scale well (requires 2^N constructor overloads where N is the number of Boolean / Custom arguments). In this case, I would use a sealed class, or prepare default instances in the companion object of my custom type (both approaches would give essentially the same API at the call site).
ComplicatedConfigurable(userOptions = UserOptions.DEFAULT, legacyLogin = LegacyLogin.DISABLED, regionSettings = RegionSettings(getUserRegion()))
Some code like this would be an example of having one feature 'enabled' (passing 'true' in your example), one 'disabled' (false), and one manually configured.