Scala学习之字符串篇(四):插值函数

本文详细介绍了Scala中字符串插值的使用方法,包括基本的变量插入、表达式使用及对象引用,并展示了如何通过f插值进行格式控制以及如何使用raw插值保留转义字符。

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

在Scala中使用字符串插值函数,需要再字符串前加上字符"s",然后再字符串中的每个插值变量前加上“$”符号。

scala> val name = "Fred"
name: String = Fred

scala> val age = 18
age: Int = 18

scala> val weight = "200"
weight: String = 200

scala> println(s"$name is $age years old, and weights $weight pounds")
Fred is 18 years old, and weights 200 pounds

除了可以使用变量外还可以在字符串插值中使用表达式代码。

scala> println(s"$age next year is ${age + 1}")
18 next year is 19
scala> println(s"$age is 18: ${age == 18}")
18 is 18: true

还可以在插值表达式中使用对象。

scala> println(s"${student.name} is ${student.age} age years old.")
Fred is 18 age years old.

Scala为我们提供了更多的字符串插值函数,比如使用"f"可以对插值打印格式进行控制,比如保留两位小数。

scala> val weight = 200
weight: Int = 200

scala> println(f"$name is $age years old, and weights $weight%.2f pounds")
Fred is 18 years old, and weights 200.00 pounds

插值函数"raw"能够让转义字符失去意义。

scala> "a\nb"
res28: String =
a
b

scala> raw"a\nb"
res29: String = a\nb

 

转载于:https://my.oschina.net/nenusoul/blog/800096

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值