Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I initialize an empty EnumSet in kotlin?

I’m pretty new to Kotlin and trying to create a sort of bitset enum where ints correspond to state and I can toggle individual states by toggling individual bits. But I’m stuck on where an object can have no state.

https://pl.kotl.in/L_fTBahVN

import java.util.*

fun main() {
    var d = Door(100, EnumSet.noneOf(Status))
}

enum class Status(intValue: Int) {
    OPEN(1),
    CLOSED(1 shl 1),
    CRACKED(1 shl 2),
    BROKEN(1 shl 3)
}

class Door(val id: Int, val status: EnumSet<Status>) {}

This code fails with the error Classifier 'Status' does not have a companion object, and thus must be initialized here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was reading another question where they said to use Status.class inside the EnumSet.noneOf, but that throws even more errors.

>Solution :

Use

EnumSet.noneOf(Status::class.java)

Status::class is similar to Status.class in Java, but gets a Kotlin kotlin.reflect.KClass instead. To get the Java java.lang.Class that EnumSet.noneOf takes, you access the java property.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading