This is just a note about ARGB color int, it is different in Kotlin and Java, and this made us get incorrect color in our projects.
// The following function will return transparent color
// Because it misses alpha value.
@ColorInt
fun getThemeColor(): Int = 0xFFB900// compile error
// "The integer literal does not conform to the expected type int"
// This is because 0xFFFFB900 is Long
@ColorInt
fun getThemeColor(): Int = 0xFFFFB900// Correct Color
@ColorInt
fun getThemeColor(): Int = 0xFFFFB900.toInt()
This is because in Kotlin literal 0xFFFFB900
will be regarded as Long
, not Int
. So we have to convert it to an integer if we want our ColorInt variable to be that type.
In JetBrains issue, it has more examples of this negative integer literals, i.e
val hi0: Int = 0x7FFFFFFF // works
val hi1: Int = 0x80000000 // error
val hi2: Int = 0xFFFFFFFF // error
val hi3: Int = 0x80000000.toInt() // works
val hi4: Int = 0xFFFFFFFF.toInt() // works
And just for interesting, I convert the Color constants from android’s Color.java into Kotlin.
// Java
@ColorInt public static final int BLACK = 0xFF000000;
@ColorInt public static final int DKGRAY = 0xFF444444;
@ColorInt public static final int GRAY = 0xFF888888;
@ColorInt public static final int LTGRAY = 0xFFCCCCCC;
@ColorInt public static final int WHITE = 0xFFFFFFFF;
@ColorInt public static final int RED = 0xFFFF0000;
@ColorInt public static final int GREEN = 0xFF00FF00;
@ColorInt public static final int BLUE = 0xFF0000FF;
@ColorInt public static final int YELLOW = 0xFFFFFF00;
@ColorInt public static final int CYAN = 0xFF00FFFF;
@ColorInt public static final int MAGENTA = 0xFFFF00FF;
@ColorInt public static final int TRANSPARENT = 0;// Kotlin
@ColorInt val BLACK = -0x1000000
@ColorInt val DKGRAY = -0xbbbbbc
@ColorInt val GRAY = -0x777778
@ColorInt val LTGRAY = -0x333334
@ColorInt val WHITE = -0x1
@ColorInt val RED = -0x10000
@ColorInt val GREEN = -0xff0100
@ColorInt val BLUE = -0xffff01
@ColorInt val YELLOW = -0x100
@ColorInt val CYAN = -0xff0001
@ColorInt val MAGENTA = -0xff01
@ColorInt val TRANSPARENT = 0
Let’s why I used to convert Java code into Kotlin manually.