Sunday, 15 February 2015

Get argument names in String Interpolation in Scala 2.10 -



Get argument names in String Interpolation in Scala 2.10 -

as of scala 2.10, next interpolation possible.

val name = "somename" val interpolated = s"hello world, name $name"

now possible defining custom string interpolations, can see in scala documentation in "advanced usage" section here http://docs.scala-lang.org/overviews/core/string-interpolation.html#advanced_usage

now then, question is... there way obtain original string, before interpolation, including interpolated variable names, within implicit class defining new interpolation strings?

in other words, want able define interpolation x, in such way when call

x"my interpolated string has $name"

i can obtain string seen above, without replacing $name part, within interpolation.

edit: on quick note, reason want because want obtain original string , replace string, internationalized string, , replace variable values. main reason want original string no interpolation performed on it.

thanks in advance.

since scala's string interpolation can handle arbitrary expressions within ${} has evaluate arguments before passing them formatting function. thus, direct access variable names not possible design. pointed out eugene, possible name of plain variable using macros. don't think scalable solution, though. after all, you'll lose possibility evaluate arbitrary expressions. what, instance, happen in case:

x"my interpolated string has ${"mr. " + name}"

you might able extract variable name using macros might complicated arbitrary expressions. suggestions be: if name of variable should meaningful within string interpolation, create part of info structure. example, can following:

case class namedvalue(variablename: string, value: any) val name = namedvalue("name", "some name") x"my interpolated string has $name"

the objects passed any* x. thus, can match namedvalue within x , can specific things depending on "variable name", part of info structure. instead of storing variable name explicitly exploit type hierarchy, instance:

sealed trait interpolationtype case class interpolationtypename(name: string) extends interpolationtype case class interpolationtypedate(date: string) extends interpolationtype val name = interpolationtypename("someone") val date = interpolationtypedate("2013-02-13") x"$name born on $date"

again, within x can match interpolationtype subtype , handle things according type.

string scala scala-2.10 string-interpolation

No comments:

Post a Comment