Interpolated Strings

本文介绍了Scala中三种插值字符串的使用方法:普通插值字符串、printf格式化的插值字符串及原始插值字符串,并通过实例展示了如何应用这些字符串来简化编程任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There are three kinds of interpolated strings.

  1. A String of the form s"foo ${bar}" will have the value of expression bar, converted to a String and inserted in place of ${bar}. If the expression bar returns an instance of a type other than String, a toString method will be invoked, if one exists. It is an error if it can’t be converted to a String.
  2. The second kind provides printf formatting and uses the prefix f.
  3. The third kind is called “raw” interpolated strings. It doesn’t expand escape characters, like \n.

code example

// The first way:
val name: String = "BrownWong"
println(s"My name is ${name}")
println(s"My name is $name") // 省略大括号

// The second way:
val money = 100F
println(f"I have ${money}%.2f $$") // "$$"输出"$"
println(f"I have $money%.2f $$")
println("I have %.2f $".format(money)) // 用字符串的format函数同样可以实现

// The third way:
println(raw"haha\nhaha")

output:

My name is BrownWong
My name is BrownWong
I have 100.00 $
I have 100.00 $
I have 100.00 $
haha\nhaha


Ref

《Programming Scala》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值