What is the Kotlin way to have a similar effect like the enum variable flag in C #

In C #, I can do this.

[Flags]
enum BeerProperty
{
    Bold = 1,
    Refreshing = 2
}

static void Taste(BeerProperty beer)
{
    if (beer == (BeerProperty.Bold | BeerProperty.Refreshing))
    {
        Debug.WriteLine("I can't qutie put my finger on...");
    }
}

static void Main(string[] args)
{
    var tickBeer = BeerProperty.Bold | BeerProperty.Refreshing;
    Taste(tickBeer);
}

In Kotlin it seems that I can’t “OR” two flags. What is the Kotlin method? Using a list of enumeration variables?

enum class BeerProperty(value:Int)
{
    Bold(1),
    Refreshing(2)
}

fun taste(beer:BeerProperty)
{
    if(beer == (BeerProperty.Bold | BeerProperty.Refreshing))
    {
        print("I can't qutie put my finger on...");
    }
}

fun main(args: Array<String>)
{
    val tickBeer = BeerProperty.Bold | BeerProperty.Refreshing;
    taste(tickBeer);
}

Added: Thank you for the answer (which I still can not mark as an answer, due to the time limit). I changed the code as shown below and achieved what I wanted.

fun taste(beer: EnumSet<BeerProperty>)
{
    if(beer.contains(BeerProperty.Bold) && beer.contains(BeerProperty.Refreshing))
    {
        print("I can't qutie put my finger on...");
    }
}

fun main(args: Array<String>)
{
    val tickBeer = EnumSet.of(BeerProperty.Bold, BeerProperty.Refreshing);
    taste(tickBeer);
}
+4
source share
2 answers

In fact, in Kotlin, each enum constant is an instance of a class corresponding to an enumeration, and you cannot use 'OR' to join multiple instances of clas. If you need to track multiple enum values, the most efficient way to do this is to use the EnumSet class .

+3
source

Using extension features

import java.util.*

enum class BeerProperty
{
    BOLD,
    REFRESHING,
    STRONG;

    infix fun and(other: BeerProperty) = BeerProperties.of(this, other)
}

typealias BeerProperties = EnumSet<BeerProperty>

infix fun BeerProperties.allOf(other: BeerProperties) = this.containsAll(other)
infix fun BeerProperties.and(other: BeerProperty) = BeerProperties.of(other, *this.toTypedArray())

fun taste(beer: BeerProperties) {
    if(beer allOf (BeerProperty.BOLD and BeerProperty.REFRESHING and BeerProperty.STRONG)) {
        print("I can't qutie put my finger on...")
    }
}

fun main(args: Array<String>) {
    val tickBeer = BeerProperty.BOLD and BeerProperty.REFRESHING and BeerProperty.STRONG
    taste(tickBeer)
}

I use extension functions to add properties, and, and allof to check all flags.

0
source

Source: https://habr.com/ru/post/1694769/


All Articles