Skip to content

Instantly share code, notes, and snippets.

Last active October 13, 2022 15:42
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Prototyping a Flags/Bitmasks implementation in Kotlin 1.1.1
class BitMask(val value: Long)
interface Flags {
val bit: Long
fun toBitMask(): BitMask = BitMask(bit)
infix fun Flags.and(other: Long): BitMask = BitMask(bit and other)
infix fun <T: Flags> Flags.or(other: T): BitMask = BitMask(bit or other.bit)
operator infix fun Flags): BitMask = BitMask(bit or other.bit)
inline fun <reified T> enabledValues(mask: BitMask) : List<T> where T : Enum<T>, T : Flags {
return enumValues<T>().filter {
mask hasFlag it
infix fun BitMask.or(other: Flags): BitMask = BitMask(value or other.bit)
operator infix fun BitMask): BitMask = BitMask(value or other.value)
operator infix fun Flags): BitMask = BitMask(value or other.bit)
infix fun <T: Flags> BitMask.hasFlag(which: T): Boolean {
// an Undefined flag is a special case.
if(value == 0L || (value > 0L && which.bit == 0L)) return false
return value and which.bit == which.bit
infix fun <T: Flags> BitMask.unset(which: T): BitMask = BitMask(value xor which.bit)
fun main(args : Array<String>){
val mask: BitMask = ParameterFeature.Path +
ParameterFeature.Query +
val enabled = enabledValues<ParameterFeature>(mask)
println("flags enabled: $enabled")
println("flags disabled: ${enumValues<ParameterFeature>().filterNot { enabled.contains(it) } }")
println("mask hasFlag ParameterFeature.Query: ${mask hasFlag ParameterFeature.Query}")
println("mask hasFlag ParameterFeature.Body: ${mask hasFlag ParameterFeature.Body}")
enum class ParameterFeature(override val bit: Long) : Flags {
Path(1 shl 0),
Query(1 shl 1),
Header(1 shl 2),
Body(1 shl 3),
FormUnencoded(1 shl 4),
FormMultipart(1 shl 5);
#!/usr/bin/env bash
kotlinc {BitMask,Flags,globals,ParameterFeature,main}.kt && kotlin MainKt
Copy link

Thank you very much for this awesome example @jimschubert

Copy link

Hidden gem

Copy link

@fabriciovergara thanks! I'm glad you've found it useful.

Copy link

nice work! very helpful for network physics

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment