RudziankoŇ≠ RudziankoŇ≠ - 4 months ago 12
Scala Question

Fetch value using 'case' in scala

I am new in scala, don't be mad at me for a nub question, please help me see how

parsing works on my example:

I want to parse such string:


So basically I want split them by
and parse the first one as
and the second one
to a such structure:

class IPAddress(val cartage1 : Integer, cartage2 : Integer, cartage3: Integer, cartage4 : Integer) {


Could you please help me to do it?

phg phg

I suppose by "case parsing" you mean the extractor of the regex class? Well, a simple variant would be the following:

scala> val pattern = """(\d+)\s+(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""".r
pattern: scala.util.matching.Regex = (\d+)\s+(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})

scala> val pattern(d, i1, i2, i3, i4) = "6546263252026003359"
d: String = 6546263252026003359
i1: String = 192
i2: String = 168
i3: String = 1
i4: String = 1

Whereby the regex should probably be worked on, if you want to ensure valid IPs.

What happens underneath is that pattern defines an unapply method of type String => Option[(Int, Int, Int, Int, Int)], so that something like

"6546263252026003359" match {
  case pattern(d, i1, i2, i3, i4) => IPAddress(i1, i2, i3, i4)

gets (roughtly) translated to this:

pattern.unapply("6546263252026003359") match {
  case Some((d, i1, i2, i3, i4)) => IPAddress(i1, i2, i3, i4)
  case None => /* throw some error */

The pattern assignment shown above works similar, it just modifies the local environment. Technicalities can be looked up here and probably in the spec.