scala中原始字符串插值和三重引号有什么区别 [英] What's the difference between raw string interpolation and triple quotes in scala

查看:57
本文介绍了scala中原始字符串插值和三重引号有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 有三重引用的字符串 """String\nString""" 来使用字符串中的特殊字符而不转义.Scala 2.10 也出于同样的目的添加了 raw"String\nString".

Scala has triple quoted strings """String\nString""" to use special characters in the string without escaping. Scala 2.10 also added raw"String\nString" for the same purpose.

raw""""""" 的工作方式有什么不同吗?他们可以为同一个字符串产生不同的输出吗?

Is there any difference in how raw"" and """""" work? Can they produce different output for the same string?

推荐答案

查看默认插值器的源代码(可在此处找到:https://github.com/scala/scala/blob/2.11.x/src/library/scala/StringContext.scala)它看起来像"raw" 插值器在每个字母上调用恒等函数,所以你输入的就是你得到的.您会发现的最大区别是,如果您在源中提供包含引号字符的字符串文字,原始插值器仍然无法工作.即你不能说

Looking at the source for the default interpolators (found here: https://github.com/scala/scala/blob/2.11.x/src/library/scala/StringContext.scala) it looks like the "raw" interpolator calls the identity function on each letter, so what you put in is what you get out. The biggest difference that you will find is that if you are providing a string literal in your source that includes the quote character, the raw interpolator still won't work. i.e. you can't say

raw"this whole "thing" should be one string object"

但你可以说

"""this whole "thing" should be one string object"""

所以你可能想知道那我为什么要费心使用原始插值器?"答案是原始插值器仍然执行变量替换.所以

So you might be wondering "Why would I ever bother using the raw interpolator then?" and the answer is that the raw interpolator still performs variable substitution. So

val helloVar = "hello"
val helloWorldString = raw"""$helloVar, "World"!\n"""

将为您提供字符串 "hello, "World"!\n" ,其中 \n 不会转换为换行符,以及单词 world 周围的引号.

Will give you the string "hello, "World"!\n" with the \n not being converted to a newline, and the quotes around the word world.

这篇关于scala中原始字符串插值和三重引号有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆