Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unapply regex matching into case class

Tags:

scala

Given a regex and a string

val reg = "(a)(b)"
val str = "ab"

and a corresponding case class

case class Foo(a: string, b: string)

How can I match the regex against the string and unapply the matches into the case class so I have

Foo("a", "b")

in the end?

like image 474
Reactormonk Avatar asked Feb 06 '13 06:02

Reactormonk


People also ask

What is the difference between Unapply and apply when would you use them?

Whereas the apply method is like a constructor which takes arguments and creates an object, the unapply takes an object and tries to give back the arguments. This is most often used in pattern matching and partial functions. The apply method creates a CustomerID string from a name .

How unapply method works in Scala?

The unapply method breaks the arguments as specified and returns firstname object into an extractor . It returns a pair of strings if as an argument, the first name and last name is passed else returns none.

What is case object in Scala?

A case object is like an object , but just like a case class has more features than a regular class, a case object has more features than a regular object. Its features include: It's serializable. It has a default hashCode implementation.


1 Answers

Pattern match on the result of finding the regular expression in the string and assigning the results to Foo. The API docs for Regex have a similar example.

scala> val reg = "(a)(b)".r
reg: scala.util.matching.Regex = (a)(b)

scala> val str = "ab"
str: String = ab

scala> case class Foo(a: String, b: String)
defined class Foo

scala> val foo = reg.findFirstIn(str) match{
     | case Some(reg(a,b)) => new Foo(a,b)
     | case None => Foo("","")
     | }
foo: Foo = Foo(a,b)

 scala> foo.a
res2: String = a

scala> foo.b
res3: String = b
like image 144
Brian Avatar answered Oct 24 '22 04:10

Brian