1

what I want to achieve in here is to compare a string with a value of an enum first, I tried it using if

object FooType extends Enumeration {
  type FooType = Value
  val FooA = Value("FA")
  val FooB = Value("FB")
}

val x = "FA"
if (x == FooType.FooA)  //Does not match
  println("success using if without toString")
if (x == FooType.FooA.toString) //match
  println("success using if with toString")

println(FooType.FooA) //will print into "FA"

at least, it still working well when I compare it to the enum with toString method. but if I change it to a match case, it would turn into an error instead

x match {
  case FooType.FooA.toString => println("success using match")
}

ScalaFiddle.scala:19: error: stable identifier required, but ScalaFiddle.this.FooType.FooA.toString found.
    case FooType.FooA.toString => println("success using match")
                      ^

is there any way to achieve this by using match case?

0

2 Answers 2

5

You have to convert the String into FooType and then use match

  object FooType extends Enumeration {
    type FooType = Value
    val FooA = Value("FA")
    val FooB = Value("FB")
  }

  val x = FooType.withName("FA")

  x match {
    case FooType.FooA => println("matched")
    case _            => println("did not match")
  }
Sign up to request clarification or add additional context in comments.

Comments

2

You are converting a type in your match case, that is not allowed, you can do something like this:

object FooType extends Enumeration {
  type FooType = Value
  val FooA = Value("FA")
  val FooB = Value("FB")
}

val x = "FA"

x match {
    case str if str == FooType.FooA.toString => println("success using match")
    case _            => println("did not match")
  }

or you can do something similar to what @Ivan Stanislavciuc suggested

x match {
    case str if FooType.withName(str) == FooType.FooA => println("success using match")
    case _            => println("did not match")
  }

Comments

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.