scala string formatting with interpolator S not wo

2019-07-30 00:25发布

问题:

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 }"""