triple quotes(""")는 스칼라에서 매우 유용한 기능이다. 

왠만한 것은 다 문자열로 만들 수 있고 멀티 라인 문자열로 만들 수 있다. 자바에서 가장 취약했던 부분을 보완한 느낌이다.



\(역슬래시) 없이 "를 마음껏 쓸 수 있고, json도 편하게 사용할 수 있다.


println("""Hello "Water" World """)

결과는 다음과 같다. 


Hello "Water" World 






처음 봤을 때는 어이없지만, "만 출력하게 할 수 있다.


println(""""""")

결과는 다음과 같다.


"



println("""  {"name":"john"} """)

결과는 다음과 같다.

  {"name":"john"} 



간단한 수식도 사용할 수 있다. 스페이스 * 8 칸..

println(s"hello,${" " * 8}world")

결과는 다음과 같다.

hello,        world



변수도 사용할 수 있다. s를 주면 문자열 바깥의 내용을 참조할 수 있게 한다.


val abc = 111
println("""Hello number ${abc} """)
println(s"""Hello number ${abc} """)

결과는 다음과 같다.


Hello number ${abc} 

Hello number 111 




간단한 수식도 사용할 수 있다. 


val trueFalse = true
println(s"""${if (trueFalse) "true" else "false"} """)


결과는 다음과 같다.


true 





if문과 객체 내부도 접근해서 사용할 수 있다.

case class Comment(val comment_type: String)

val comment = Comment("sticker")
println(s"""${if (comment.comment_type.isEmpty) "X" else comment.comment_type} """)

결과는 다음과 같다.


sticker 




triple quote 앞에 f를 사용하면 문맥에 맞게 출력된다.

println(f"""c:\\user""")
println("""c:\\user""")

결과는 다음과 같다.


c:\user

c:\\user




스칼라는 변수명의 제한이 없는데 특수문자로 변수명으로 사용할 수 있고, 이를 triple quotes에서 사용할 수 있다. 

val `"` = "\""
println(s"${`"`}")

val % = "bbb"
//val `%` = "bbb" // 동일함
println(s"${`%`}")




멀티 라인도 지원한다.

val m =
"""Hi
|This is a String!"""
println(m)

결과는 다음과 같다.


Hi

      |This is a String!




공백 이슈가 있다. 이를 제거하려면 다음을 실행한다.


val s =
"""Hi
|This is a String!""".stripMargin
println(s)


결과는 다음과 같다.


Hi

This is a String!




간단하게 문자열 조작을 stripXXX로 실행할 수 있다. 

val s1 =
"""Hi
|This is a String!""".stripPrefix("Hi").stripSuffix("!").stripMargin
println(s1)

결과는 다음과 같다.



This is a String





"""안에 불필요한 \n\r\b 이런 것들을 몽땅 날리기 위해 StringContext.treatEscapes를 포함시켜 실행한다. 

val s2 =
StringContext.treatEscapes(
"""StringContext.
|treatEscapes!\r\n""".stripMargin)
println(s2)

결과는 다음과 같다.


StringContext.

treatEscapes!





간단히 함수로 묶을 수도 있다. 


def hello(name: String) =
s"""
|Hello, $name
|Come to with your family to World
""".stripMargin

println(hello("samuel"))



결과는 다음과 같다.


Hello, samuel

Come to with your family to World


Posted by '김용환'
,