implicit conversion - Scala: "number" interpolation -
scala has string interpolation raw"\n" raw strings.
does have number interpolation e.g. 1px 1 pixel? nice syntax numeric units both make code more readable , make easier write safer code.
like strings, numbers have nice literal syntax , fundamental.
prefix notation px(1) not how people write units:
case class px(n: int) and don't think postfix notation via implicit conversion can work:
case class pixels(n: int) { def px() = pixels(n) def +(p: pixels) = p match {case pixels(m) => pixels(n+m)} } implicit def int2pixels(n: int) = pixels(n) it needs dot or space or parens (i.e. not
(1 px)or(1)pxor1.px, not how humans write units).it won't check types i.e. want explicitly cast between these numeric type-alias things , numbers (i.e.
1.px + 2,1 + 2.px,def inc(p: pixels) = p + pixels(1)inc(0)don't fail, because of implicit cast, when should).
you can define own string interpolation (more details here):
implicit class unithelper(val sc : stringcontext) extends anyval { def u(args: any*): pixels = { val pxr = """(\d.*)\s*px""".r sc.parts.mkstring match { case pxr(px) => pixels(px.toint) case _ => throw new illegalargumentexception } } } usage example:
val x = u"10px" + u"20px" // x = pixels(30) pros:
- easy add interpolation units: em, px, pt, cm, in
cons:
- it not type safe because string interpolation runtime feature.
Comments
Post a Comment