Can anyone help me out with the preferred (i.e the Kotlin way) to implement flags in Kotlin?
I have a couple of utility classes for converting Speed and Distance values to different units and formatting the results as strings. So far I’ve only needed to specify whether the resulting string contains the unit suffix or not (e.g “25 MPH” or just “25” etc) so my format function just takes a boolean “withSuffix” paramater which I have defaulted to ‘true’
I now find that I want to expand on the formatting options, so I would like to replace the “withSuffix” paramater with “formatOptions” value. In Java, C/C++ I’d use an integer bitmap of options:
enum FormatOptions {
WITH_SUFFIX = 1 << 0,
WITH_DECIMAL = 1 << 1
// Etc...
}
And just bitwise OR the flags together.
I know Kotlin has the “Or” and “Shl” I need but I can’t find any examples of people actually using them for this purpose.
When I’ve searched I’ve found some suggestions that EnumSet (from the Java runtime) is the way to go.
I’d like to default the formatOptions
parameter to an empty set, so, I am trying to do something like this using the EnumSet.noneOf() function:
enum class FormatOptions {
WITH_SUFFIX,
WITH_DECIMAL
}
fun formatSpeed(speed: Float, sourceUnit: SpeedUnit, format: Format, formatOptions: EnumSet<FormatOptions> = EnumSet.noneOf(FormatOptions.class)): String {
}
But for some reason the Kotlin compiler is not recognising the “class” property of the FormatOptions enum. Unfortunately all the examples I can find are in Java and the method of instanciating an empty EnumSet is shown as:
EnumSet<MyEnum> theSet = EnumSet.noneOf(MyEnum.class)
So in Kotlin it should be something like
val theSet: EnumSet<MyEnum> = EnumSet.noneOf(MyEnum.class)
or
val theSet = EnumSet.noneOf(MyEnum.class)
But I can get this to work in Kotlin, the compiler complains that “class” is unknown
Am I missing something and is there a better way to do this? (I thought about creating an Options class and passing something like Options.apply { withSuffix = true, withDecimal = false } but I am not too keen on that)
Cheers