Better String formatting in Scala

前端 未结 7 1296
孤独总比滥情好
孤独总比滥情好 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:49

    Well, if your only problem is making the order of the parameters more flexible, this can be easily done:

    scala> "%d %d" format (1, 2)
    res0: String = 1 2
    
    scala> "%2$d %1$d" format (1, 2)
    res1: String = 2 1
    

    And there's also regex replacement with the help of a map:

    scala> val map = Map("number" -> 1)
    map: scala.collection.immutable.Map[java.lang.String,Int] = Map((number,1))
    
    scala> val getGroup = (_: scala.util.matching.Regex.Match) group 1
    getGroup: (util.matching.Regex.Match) => String = 
    
    scala> val pf = getGroup andThen map.lift andThen (_ map (_.toString))
    pf: (util.matching.Regex.Match) => Option[java.lang.String] = 
    
    scala> val pat = "#\\{([^}]*)\\}".r
    pat: scala.util.matching.Regex = #\{([^}]*)\}
    
    scala> pat replaceSomeIn ("This is #{number} string", pf)
    res43: String = This is 1 string
    

提交回复
热议问题