字面量
字面量就是直接在代码中写常量值(constant value)的方式
种类
- 整型字面量(Integer Literals)
- 浮点字面量(Floating Point Literals)
- 字符字面量(Character Literals)
- 字符串字面量(String Literals)
- 符号字面量(Symbol Literals)
- 布尔字面量(Boolean Literals)
字符串插值
Scala 使用一种灵活的(flexible)的方式来组合字符串,叫做字符串插值
三种方式
-
s"$variable ${expression}"
,表达式当中的值可以进行运算 -
raw"$variable ${expression}"
,不执行转义 -
f"$variable ${expression}[%_]"
, 默认是%s,执行格式化
字符串插值的原理
字符串插值在编译期会被编译器重写代码。编译器对待任何字符串字面量表达式,只要是标识符紧跟着一个右双引号(open double quote),就会被看做成字符串插值。
通过这个机制,类库或者用户可以自己定义特殊用途的字符串插值
包装类
基本类型 | 包装类 |
---|---|
Basic | type Rich wrapper |
Byte | scala.runtime.RichByte |
Short | scala.runtime.RichShort |
Int | scala.runtime.RichInt |
Long | scala.runtime.RichLong |
Char | scala.runtime.RichChar |
Float | scala.runtime.RichFloat |
Double | scala.runtime.RichDouble |
Boolean | scala.runtime.RichBoolean |
String | scala.collection.immutable.StringOps |