3

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
1
  • Which prefix do you mean? The class prefix like Color.red? Commented Dec 30, 2020 at 19:50

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but the first code in your examle won't compile
@Alex Craft you are right. Will update my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.