String interpolation in Scala?

后端 未结 5 1225
粉色の甜心
粉色の甜心 2021-01-04 04:43

I wanted to ask if there is any type of string interpolation in Scala. I have made a search on the subject but \'till now I have found that there is no string interpolation.

相关标签:
5条回答
  • 2021-01-04 04:47

    It's not in the (released) scala library yet. But there is a SIP (Scala Improvement Process) for the addition of this feature:

    http://docs.scala-lang.org/sips/pending/string-interpolation.html

    0 讨论(0)
  • 2021-01-04 04:51

    You can do it C-style:

    "Interpolate my %s here" format List(1,2,3)
    
    //String = Interpolate my List(1, 2, 3) here
    

    or

    List(1,2,3) formatted "Interpolate my %s here"
    

    You can use these on anything with a toString (i.e. anything)

    case class Foo(n: Int)
    Foo(42) formatted "Here is a %s !!!!"
    //String = Here is a Foo(42) !!!!
    

    although the former is more flexible in terms of enabling multiple interpolations in a single string (since it can take multiple arguments).

    0 讨论(0)
  • 2021-01-04 04:52

    This days (Dec. 2016, Scala 2.12, five years later), you can write your own string interpolation.
    See co.ntextu.al

    Contextual is a small Scala library which allows you to define your own string interpolators—prefixed string literals like uri"https://google.com" which determine how they should be evaluated, at runtime and at compile-time, while only writing very ordinary user code: no macros!

    For instance, contextual/examples/email.scala allows to check at compile time the validity of an email address.

    import contextual.examples.email._
    email"""info@scala.world"""
    
    import contextual.examples.email._
    email"""john.smith@hotmail.com"""
    
    0 讨论(0)
  • 2021-01-04 05:01

    yes, there is string interpolation in current scala releases via compiler plugin see http://jrudolph.github.com/scala-enhanced-strings

    0 讨论(0)
  • 2021-01-04 05:09

    I use the xml hack on scala 2.9

    val age = 28
    val name = "Gerry"
    
    <a>My name is {name} and I am {age} years old</a>.text
    res0: String = My name is Gerry and I am 28 years old
    
    0 讨论(0)
提交回复
热议问题