Better String formatting in Scala

前端 未结 7 1271
孤独总比滥情好
孤独总比滥情好 2020-12-02 12:03

With too many arguments, String.format easily gets too confusing. Is there a more powerful way to format a String. Like so:

\"This is #{number}          


        
7条回答
  •  一整个雨季
    2020-12-02 12:43

    If you're using 2.10 then go with built-in interpolation. Otherwise, if you don't care about extreme performance and are not afraid of functional one-liners, you can use a fold + several regexp scans:

    val template = "Hello #{name}!"
    val replacements = Map( "name" -> "Aldo" )
    replacements.foldLeft(template)((s:String, x:(String,String)) => ( "#\\{" + x._1 + "\\}" ).r.replaceAllIn( s, x._2 ))
    

提交回复
热议问题