How to insert double quotes into String with interpolation in scala

后端 未结 11 1578
北荒
北荒 2020-12-05 12:53

Having trouble escaping all the quotes in my function

(basic usage of it -> if i find a string do nothing, if its not a string add \" in the begin and end)

11条回答
  •  情歌与酒
    2020-12-05 13:16

    Taking @Pascalius suggestion a few steps further. class StringImprovements extends and inherits AnyVal.

    object StringUtil{
        implicit class StringImprovements(val s: String) extends AnyVal {
            def dqt = "\""+s+"\""    // double quote
            def sqt = s"'$s'"        // single quote
        }
    }
    

    Scala only uses the StringImprovements class to create an intermediate object on which to call implicitly the two extension methods dqt & sqt. Nevertheless, we can eliminate the creation of this object and improve performance by making the class inherit from AnyVal. For Scala provides the value type specifically for such cases where the compiler will replace the object by just making the call to the method directly.

    Here is a simple example using the above implicit class in an intermix where we use named variables (string & boolean) and a function in the interpolation string.

    import StringUtil._
    abstract class Animal {
       ...
       override def toString(): String = s"Animal:${getFullName().dqt}, CanFly:$canFly, Sound:${getSound.dqt}"
     }
    

提交回复
热议问题