Reputation: 33293
I have an object Foo
object Foo extends RegexParsers{
def apply(s:String): Array[String] = parseAll(record, line) match {
// some logic
}
def record = repsep(mainToken, ",")
// some more code
def unquotes = "[^,]+".r
}
Now this is pretty hardcoded for comma separated string..
I want to basically modify this function to basically account for another case (tab seperated)..
For which the following code works
object Foo extends RegexParsers{
def apply(s:String): Array[String] = parseAll(record, line) match {
// some logic
}
def record = repsep(mainToken, "\t") // change here
// some more code
def unquotes = "[^\t]+".r // change here
}
Just two changes...
How do I merge these two changes.. where I can take this delimiter as an argument.. (default argument comma)... and then based on that.. execute the required code.. ?? Thanks
Upvotes: 0
Views: 61
Reputation: 10904
A solution by just adding a var.
This would also work:
object Foo extends RegexParsers{
// make sep a var
var sep : String = ","
def apply(s:String): Array[String] = parseAll(record, line) match {
// some logic
}
def record = repsep(mainToken, sep)
// some more code
def unquotes = ("[^" + sep + "]+").r
}
For changing the separator just do:
Foo.sep = "\t"
But beware no you have added mutable State and you could run in problems when the code is run asynchronously or in parallel.
Upvotes: 1
Reputation: 206926
You could make Foo
a class instead of an object, and pass the desired separator character as a constructor argument.
class Foo(separator: Char) extends RegexParsers {
def apply(s:String): Array[String] = parseAll(record, line) match {
// some logic
}
def record = repsep(mainToken, separator.toString)
def unquotes = ("[^" + separator + "]+").r
}
Then use it by making the appropriate instance:
// Parser that uses comma as the separator
val foo1 = new Foo(',')
// Parser that uses tab as the separator
val foo2 = new Foo('\t')
Upvotes: 2