Home > Enterprise >  How can I iterate over my Enumeration values that contain a particular value?
How can I iterate over my Enumeration values that contain a particular value?

Time:09-17

I have an enumeration that currently for some reason is not outputting anything when I loop over the values:

 object UserType extends Enumeration {
    type UserType = UTValue

    protected case class UTValue(name: String, roles: Set[String]) extends super.Val {
     // override def toString(): String = name
    }

    val anonymous = UTValue("anonymous", Set.empty)
    val superUser = UTValue("super", Set("member", "admin", "edit", "delete"))
  }

  println(UserType.anonymous)
  println(UserType.superUser)
  println(UserType.values.map(println))

The output is:

anonymous
superUser
anonymous
superUser
TreeSet(())

Why is an empty TreeSet(()) being returned?

My main question: How can I iterate over all the Enumeration values that contain the role "member".

UserType.values.filter(_.roles.contains("member"))

(scala 2.13.x)

CodePudding user response:

You are printing value inside the map and println returns Unit, if you remove println inside the map like println(UserType.values.map(value => value))

 object UserType extends Enumeration {
    type UserType = UTValue

    protected case class UTValue(name: String, roles: Set[String]) extends super.Val {
      // override def toString(): String = name
    }

    val anonymous = UTValue("anonymous", Set.empty)
    val superUser = UTValue("super", Set("member", "admin", "edit", "delete"))
  }

  println(UserType.anonymous)
  println(UserType.superUser)
  println(UserType.values.map(x => x))

And since it is TreeSet it removes duplicate values and keeps only one Unit value (), that is why you are getting TreeSet(())

CodePudding user response:

You need implicit conversion in UserType.

object UserType extends Enumeration {
    type UserType = UTValue

    protected case class UTValue(name: String, roles: Set[String]) extends super.Val {
        // override def toString(): String = name
    }

    val anonymous = UTValue("anonymous", Set.empty)
    val superUser = UTValue("super", Set("member", "admin", "edit", "delete"))

    import scala.language.implicitConversions
    implicit def valueToUTValue(x: Value): UTValue = x.asInstanceOf[UTValue]
}

UserType.values.filter(_.roles.contains("member")).foreach(println)
  • Related