[英]Bidirectional string conversion in scala
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. 它是Parser组合器的简单替代方法,对我来说更有用,因为我可以使用相同的表达式从字符串中读取和写入日期。
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? 有没有更简单的方法来编写上面的代码,尤其是
converter"...."
这样我仍然可以不应用并以类似方式应用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.