https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
t

Tiago Nunes

05/21/2021, 4:03 PM
Hey everyone, is there any way to specify the values for common fields of an enum class in commonMain? This is what I know works: commonMain:
Copy code
expect enum class ImageTargetType {
    USER,
    DEVICE;

    val code: String
}
androidMain:
Copy code
actual enum class ImageTargetType(
    actual val code: String,
    @DrawableRes val defaultImageResId: Int?,
) {
    USER("User", R.drawable.ic_default_user),
    DEVICE("Device", null),
}
This is what I wanted: commonMain:
Copy code
expect enum class ImageTargetType(val code: String) {
    USER("User"),
    DEVICE("Device);
}
androidMain:
Copy code
actual enum class ImageTargetType(
    @DrawableRes val defaultImageResId: Int?,
) {
    USER(R.drawable.ic_default_user),
    DEVICE(null),
}
r

russhwolf

05/21/2021, 4:26 PM
I don't think it's possible the way you're trying, but maybe you can use two different types instead
Copy code
// common
enum class CommonImageTargetType(val code: String) {
    USER("User"),
    DEVICE("Device);
}

// android
enum class AndroidImageTargetType(
    val commonImageTargetType: CommonImageTargetType,
    @DrawableRes val defaultImageResId: Int?,
) {
    USER(CommonImageTargetType.USER, R.drawable.ic_default_user),
    DEVICE(CommonImageTargetType.DEVICE, , null),
}
t

Tiago Nunes

05/21/2021, 6:38 PM
Thanks @russhwolf that's a great idea! But then the compiler doesn't force me to specify all entries of the enum
r

russhwolf

05/21/2021, 6:40 PM
Yeah, there's always tradeoffs
If you add functions to convert between them then you can recover that compile-safety with when checks
fun CommonImageTargetType.toAndroidImageTargetType() = when { ... }
you're still vulnerable to copy-paste errors if you associate the wrong values together, but that's a lower risk probably
t

Tiago Nunes

05/21/2021, 6:46 PM
Hm that's also a good idea, if there are lots of common fields it might be the best solution
4 Views