scala string formatting with interpolator S not working

蹲街弑〆低调 提交于 2019-12-11 05:57:46

问题


I am new to scala and trying to do some string formatting.

val mAPRegisterResponseMessage = s"{\" 'type' \": \"ap_register_response\",  
 \"message_id\": 02,\"register_status\": $registerStatus,\"host_name_type\": 
 $host_name_type, \"host_name\": $host_name, \"port_num\":$port_num }"

If I remove the s in the beginning then the string literal is formed but obviously not correctly. However after adding s at the start, I get an error as unclosed character literal for the second backslash. What am I doing wrong? Any clues will help.


回答1:


You can use triple quote:

s""" {"foo" : 2, "bar": $registerStatus} """

Scala console:

scala> val registerStatus = "new"
registerStatus: String = new

scala> s""" {"foo" : 2, "bar": $registerStatus} """
res0: String = " {"foo" : 2, "bar": new} "



回答2:


Solution 1: triple quotes (""")

as already stated by @mgosk

s""" {"foo" : 2, "bar": $registerStatus} """

Solution 2: JSON Library

It looks like you want to create JSON output. For that usecase using string interpolation is not the preferred solution. There are many libraries like for example JSON4s http://json4s.org/ that allow you to use a typesafe case class and render this then as a JSON string




回答3:


String Interpolation in Scala is does not work well with escape using \. You can use """ in the case of special characters.

val mAPRegisterResponseMessage = s"""{" 'type' ": "ap_register_response", "register_status": $registerStatus }"""


来源:https://stackoverflow.com/questions/38972841/scala-string-formatting-with-interpolator-s-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!