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?
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With