Alex Craft
Alex Craft

Reputation: 15336

Use enum names without prefix in Kotlin?

Is it possible to use enum name without its prefix?

enum class Color { red, blue, green }

data class Shape(val color: Color)

fun main() {
    println(Shape(color = red))
}

P.S.

Or maybe it has something like literal types in TypeScript? I don't actually need Enum, the string value would be fine as soon as the Compiler would be able to check the values at compile time, like in TypeScript.

type Color = 'red' | 'blue' | 'green'

class Shape {
    constructor(public color: Color) {}
}

console.log(new Shape('red')) // Will be validated at compile time

Upvotes: 3

Views: 699

Answers (1)

ChristianB
ChristianB

Reputation: 2680

Yes, you can use an enum without the class prefix if you import it:

import Color.*

enum class Color { Red, Blue, Green }

val color = Red

Note: By convention, enum names should start with an uppercase letter.

Edit

First I thought it would be possible to not import the enum when you use it within the same file but in a different class or top-level function, but you still have to import it - to avoid the class prefix.

Upvotes: 4

Related Questions