Scala Snippet as Java -
i'm working way through scala project, , converting java. everythings going fine, i'm stumbled snippet:
pattern filenamepattern = pattern.compile("^(\\w+).*(_\\w+\\.xml)$"); new file(filepath).getname match { case filenamepattern(first, last) => return first + last case n => return n }
i understand regex, 1 or more letters, numbers or punctuation, followed 0 or more characters, followed 1 or more letters, numbers or punctuation. purpose of function file name file path, straight forward in java, have thought scala developer wouldn't make needlessly complex.
the problem is, don't want march ahead , assume developer idiot, when maybe they're trying little more clever, , lack of experience scala stopping me seeing it. please explain:
- the syntax match
- where hell first , last came from
- the equivalent / documentation leads java equivalent of snippet
def getfilename(filepath: string): string = { if(filepath == null || filepath.trim.length == 0) { return filepath } val filenamepattern = new regex("^(\\w+).*(_\\w+\\.xml)$") new file(filepath).getname match { case filenamepattern(first, last) => return first + last case n => return n } }
the match
construct used pattern matching. basically, left-hand side of match
object match against patterns present in right-hand side. generated code tests each pattern in order appear, , if pattern matches object, code after =>
executed.
the first
, last
variables in match
expression variables bound pattern matching machinery, when pattern, appear in, matches object. values corresponding value in object graph being matched. in other word, implicitly declared pattern, , initialized in "consequence" clause after =>
.
classic example:
trait expr case class const(val value: int) extends expr case class add(val left: expr, val right: expr) extends expr def evaluate(exp: expr): int = exp match { case const(cv) => cv case add(exp1, exp2) => evaluate(exp1) + evaluate(exp2) case _ => throw new illegalargumentexception("did not understand: " + exp) }
scala's regular expression objects have provide special support pattern matching (via unapply
/unapplyseq
method). in case, if regular expression matches against string returned getname
, variables first
, last
bound substring matching first subgroup of regular expression, , second subgroup respectively.
java has no match
language construct. equivalent java code quite longish , troublesome. might like
final string name = (new file(filepath).getname()); final matcher matcher = filenamepattern.match(name); if (matcher.matches()) { final string first = matcher.group(1); final string last = matcher.group(2); return first + last; } else { return name; }
Comments
Post a Comment