简体   繁体   中英

Dedicated Scala String interpolation

For a given Map of constants

val ctt = Map("a" -> 1, "b" -> 2)

how to define a String interpolator c where

c"a" 

delivers List(1) ?

Note Already considered String Interpolation but still unclear how to proceed.

Update

c"a,b"
res: List(1,2)

c" a, b  "
res: List(1,2)

c"a,w"
res: List(1)

c"w"
res: List()

The following works:

scala> val ctt = Map("a" -> 1, "b" -> 2)
ctt: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2)

scala> implicit class CttHelper(val sc: StringContext) extends AnyVal {
     |   def c(args: Any*): Int = ctt(sc.parts.head)
     | }
defined class CttHelper

scala> c"a"
res0: Int = 1

Or for your updated version:

implicit class CttHelper(val sc: StringContext) extends AnyVal {
  def c(args: Any*): List[Int] =
    sc.parts.head.split(',').map(_.trim).toList.flatMap(ctt.get)
}

And then:

scala> c"a,w"
res5: List[Int] = List(1)

scala> c"a,b"
res6: List[Int] = List(1, 2)

scala> c" a, b  "
res7: List[Int] = List(1, 2)

scala> c"a,w"
res8: List[Int] = List(1)

scala> c"w"
res9: List[Int] = List()

You probably want to check that sc.parts has a single element, though, unless you actually want to do something with interpolated variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM