6. Approach #4: Creating a findBy() Function for Any Enum With a Value So far, we’ve seen three approaches to solve the problem. However, all these three solutions need to add some functions to the enum class. If our project has many enum classes that require this “findBy” feature...
自Kotlin 1.1 起,可以使用 enumValues<T>() 和enumValueOf<T>() 函数以泛型的方式访问枚举类中的常量。 1.4.1、访问枚举变量属性 例: fun main(args: Array<String>) { println("name = " + Color.RED.name + "\tordinal = " + Color.RED.ordinal) println("name = " + Color.WHITE.name + "...
inline fun <reified T : kotlin.Enum<T>> safeValueOf(type: String?): T? { return java.lang.Enum.valueOf(T::class.java, type) } 由于以下原因,下面的示例无法编译: 在inline fun <reified T : kotlin.Enum<T>> safeValueOf(type: kotlin.String?): T?中为T绑定的类型参数不满足:推断类型Test...
enumclassColor(val r:Int,val g:Int,val b:Int//声明枚举常量的属性){RED(255,0,0),//当每个变量创建的时候,指定属性值ORANGE(255,165,0),//逗号是必须的YELLOW(255,255,0),GREEN(0,255,0),BLUE(0,0,255),INDIGO(75,0,130),VIOLET(238,130,238);funrgb()=(r*256+g*256+b*256)//定义...
enum class Direction { NORTH, SOUTH, WEST, EAST } enum class Color(val rgb: Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF) } 1. 2. 3. 4. 5. 6. 7. 8. 9. 枚举常量的匿名类 要实现枚举常量的匿名类,则必须提供一个抽象方法(必须重写的方法)。且该方法定义在枚举类内部。而...
fun enumContains(name: String): Boolean { return enumValues<Months>().any { == name } } fun main(args: Array<String>) { if (enumContains("")) { println(Months.valueOf("")) } else { println("The string value does not match with any of the enum constants.") //this gets printe...
*/ @SinceKotlin("1.1") public inline fun <reified T : Enum<T>> enumValueOf(name: String): T 我们可以这样使用原生类型数组: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 val x: IntArray = intArrayOf(1, 2, 3) x[0] = x[1] + x[2] 5.字符串类型String 字符串用 String 类型...
val ctrl = enumValueOf<VaadinKeyModifier>("CONTROL") 作为一个较少的error-prone选项,我建议创建辅助枚举,复制VaadinKeyModifier的值,并将converter转换为VaadinKeyModifier类型: enum class Modifier { SHIFT, CONTROL, ALT, ALT_GRAPH, META; fun toVaadinKeyModifier() : VaadinKeyModifier = enumValueOf(name...
enumclassDirection{ NORTH, SOUTH, WEST, EAST } 在枚举中我们也可以定义方法和属性, 这个Swift和Kotlin是一样的. Optionals 虽然Swift的optional type和Kotlin的nullable type看起来是类似的(都是具体类型后面加个问号), 但实际上它们还是有点不同.
enum class TimeInterval { DAY, WEEK, YEAR } data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { if (year != other.year) return year - other.year if (month != other.month) return month - ...