0

The below code takes the first two character of string and check if pattern is "de" or None it returns None else it returns the Test("Found")

val s =Option("abc")
val t = s.map(_.take(2))
case class Test(id:String)

t match {
  case Some("de") => None
  case None => None
  case _ => Test("Found")
}

Can anyone suggest a efficient solution for case matching

2
  • What is the question? Commented Oct 23, 2017 at 14:26
  • edited question please check Commented Oct 23, 2017 at 14:27

2 Answers 2

2

I think I get what you're asking so let me try this:

val condition = Option("abc").exists(_.toLower.take(2) == "de")
val output: Any = if(condition) Test("found") else None

The first portion returns false if the Option is None. It also returns false if the first two letters of the string are "de" in a case insensitive way.

The second portion returns either a None or a Test object. However, I want to point out that this results in an Any. Did you mean for it to return a Option[Test] type instead?

Sign up to request clarification or add additional context in comments.

1 Comment

yes return type to be Option[Test] not Any
1

I assume, you meant Some(Test("Found")) in the last line of your snippet, judging from your comment to the other answer. If so, this is what you are looking for:

t.filterNot(_.take(2) == "de").map(_ => Test("Found"))

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.