scala string formatting with interpolator S not wo

2019-07-30 00:06发布

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.

3条回答
▲ chillily
2楼-- · 2019-07-30 00:56

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 }"""
查看更多
爷的心禁止访问
3楼-- · 2019-07-30 01:00

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

查看更多
爷的心禁止访问
4楼-- · 2019-07-30 01:08

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} "
查看更多
登录 后发表回答