Bidirectional string conversion in scala

101 views Asked by At

I wanted to be able to write the following code snippet:

val Converter = converter"const1:$F;array:$AF"

val styleinput = "const1:1.2;const2:4.5,3,5,0;end"
val Converter(float1, array) = styleinput
// ... Use float1 = 1.2 and array= {4.5,3,5,0}
val styleoutput = Converter(float1, array)
assert(styleoutput == styleinput)

It is a simpler replacement of Parser combinators and in my case much more useful because I could use the same expression to both read and write the date from string.

For the conversion part, I wrote an implicit class with custom functions of mine, which resemble combinators.

def F = FloatConverter()       // Extends Converter1[Float]
def AF = RepConverter(F, ",")  // Extends Converter1[List[Float]]

implicit class ParserImplicit(sc: StringContext) {
  def converter[A](arg1: Converter1[A]) = {
    <##(##>(Const(sc.parts(0)), arg1), Const(sc.parts(1)))
  }
  def converter[A, B](arg1: Converter1[A], arg2: Converter1[B]): ConverterSeq[A, B] = {
    ###(<##(##>(Const(sc.parts(0)), arg1), Const(sc.parts(1))), <##(arg2, Const(sc.parts(2))))
  }
}

But this is very complicated. Is there a simpler way to write the code above, especially the converter"...." so that I can still use unapply and apply in a similar way?

1

There are 1 answers

0
Rob Starling On

Take a look at parboiled for inspiration and/or a solution.