Anybody else doing expect/actual abstraction over ...
# multiplatform
e
Anybody else doing expect/actual abstraction over color values? I’m trying to have a shared color palette between my apps but getting a compiler NPE when i reference UIColor constants: https://youtrack.jetbrains.com/issue/KT-38850
s
Interesting. I’m sharing my colors as integers and wrapping it with NSColor() at usage sites so haven’t run into this yet.
e
looks like i can get around it by just specifying the colors by calling the actual UIColor constructor for now
o
What I do: common
Copy code
expect class Color

expect fun fromRGB(r: Int, g: Int, b: Int): Color
expect fun fromARGB(a: Int, r: Int, g: Int, b: Int): Color
android
Copy code
actual typealias Color = Int

actual fun fromRGB(r: Int, g: Int, b: Int): Color = fromARGB(255, r, g, b)
actual fun fromARGB(a: Int, r: Int, g: Int, b: Int): Color = a shl 24 or (r shl 16) or (g shl 8) or b
iOS
Copy code
@Suppress("CONFLICTING_OVERLOADS") actual typealias Color = UIColor

actual fun fromRGB(r: Int, g: Int, b: Int) = UIColor(red = r / 255.0, green = g / 255.0, blue = b / 255.0, alpha = 1.0)
actual fun fromARGB(a: Int, r: Int, g: Int, b: Int) = UIColor(red = r / 255.0, green = g / 255.0, blue = b / 255.0, alpha = a / 255.0)
JS
Copy code
actual typealias Color = String

fun toHex(number: Int) =
    if (number >= 16) number.toString(16)
    else "0${number.toString(16)}"

actual fun fromRGB(r: Int, g: Int, b: Int): Color =
    "#${toHex(r)}${toHex(g)}${toHex(b)}".toUpperCase()

actual fun fromARGB(a: Int, r: Int, g: Int, b: Int): Color =
    "#${toHex(a)}${toHex(r)}${toHex(g)}${toHex(b)}".toUpperCase()
🙏🏼 1
e
nice
o
Indeed, we have test cases in every platform to validate it
👍 1