2
object Test {
   def main(args: Array[String]) {
       val text = "str1"
       text match {
           case "str" => println("str")

           // how to match result return by 'test' methed?
           case test("str", 1) => println("str1")
        }
    }
    def test(str: String, i: Int): String = str + i
}

How do I match the result returned by the test() method?

The test method returns a String - str1

Should I define a case class?

2 Answers 2

4

The value used in the case cannot be a function call. You could achieve what you want in a couple of ways. Either define a val to be equal to the method call's result before the match code, and use that val in the case statement (note that the val name will need to start with a capitol letter as this is special syntax to tell the compiler to use the val, not simply assign the name to the vlaue under test), like this:

val text = "str2"
val Check = test("str", 1)
text match {
    case "str" => println("str")

    // how to match result return by 'test' methed?
    case Check => println("str1")
}

Or else use a filter in the case statement, as follows:

case str if (str == test("str", 1)) => println("str1")
Sign up to request clarification or add additional context in comments.

Comments

1

To define custom matching, you need to define an extractor (an object with an unapply method). Implementing that requires parsing the string. Here's some code that does that using parser combinators:

case class StringAndNumber(string: String, number: Int)

object Test {
  def unapply(s: String): Option[StringAndNumber] = Parser(s)
}

object Parser extends scala.util.parsing.combinator.RegexParsers {

  def apply(s: String): Option[StringAndNumber] =
    parseAll(stringAndNumber, s) match {
      case Success(x, _) => Some(x)
      case _ => None
    }

  lazy val stringAndNumber = string ~ number ^^
    { x => StringAndNumber(x._1, x._2) }

  lazy val string = "[^0-9]*".r

  lazy val number = "[0-9]+".r ^^ { _.toInt }
}

def foo(s: String): String = s match {
  case "str" => "str"
  case Test(san) => s"${san.string}|${san.number}"
  case _ => "?"
}

// prints: "str, str|2, ?"
println ( Seq("str", "str2", "2str").map(foo(_)).mkString(", ") )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.