String 可以通过 trimMargin() 方法来删除多余的空白。
fun main(args: Array<String>) {
val text = """
|多行字符串
|菜鸟教程
|多行字符串
|Runoob
""".trimMargin()
println(text) // 前置空格删除了}默认 | 用作边界前缀,但你可以选择其他字符并作为参数传入,比如 trimMargin(">")。
字符串模板
字符串可以包含模板表达式 ,即一些小段代码,会求值并把结果合并到字符串中。 模板表达式以美元符($)开头,由一个简单的名字构成:
fun main(args: Array<String>) {
val i = 10
val s = "i = $i" // 求值结果为 "i = 10"
println(s)}或者用花括号扩起来的任意表达式:
fun main(args: Array<String>) {
val s = "runoob"
val str = "$s.length is ${s.length}" // 求值结果为 "runoob.length is 6"
println(str)}原生字符串和转义字符串内部都支持模板。 如果你需要在原生字符串中表示字面值 $ 字符(它不支持反斜杠转义),你可以用下列语法:
fun main(args: Array<String>) {
val price = """
${'$'}9.99
"""
println(price) // 求值结果为 $9.99}

刘义
iml***i@aliyun.com
这里我把 a 的值换成 100,这里应该跟 Java 中是一样的,在范围是 [-128, 127] 之间并不会创建新的对象,比较输出的都是 true,从 128 开始,比较的结果才为 false。
刘义
iml***i@aliyun.com
RomanLuo
rom***luo@vipshop.com
RomanLuo
rom***luo@vipshop.com
Microbubu
mic***ubu@live.com
RomanLuo 这个说法有误导性:
这里判断为地址相同不是因为有没有显示声明类型,而是类型都相同,都是数值类型,没有进行装箱操作。而案例中的类型是 Int? 可空类型,类型不同所以必须装箱,导致产生一个新对象。
Microbubu
mic***ubu@live.com
xkj
xkj***n@gmail.com
@刘义 的说法是对的,但不完整;@RomanLuo 的说法也对,但也只在 [-128, 127] 范围之外有效。
下面给一个完整的用例,包含了所有情况,供大家参考。
注意其中 Int 和 Int? ,127 和 128 之间的区别。
// Int? Int? Int?val a1: Int? = 128var boxedA: Int? = a1var boxedB: Int? = a1 log(" boxedA === boxedB ? " + (boxedA === boxedB))//truelog(" boxedA == boxedB ? " + (boxedA == boxedB))//true// Int Int? Int?val a2: Int = 128boxedA = a2 boxedB = a2 log(" boxedA === boxedB ? " + (boxedA === boxedB))//false//值相等log(" boxedA == boxedB ? " + (boxedA == boxedB))//true// Int? Int? Int?val a3: Int? = 127boxedA = a3 boxedB = a3 log(" boxedA === boxedB ? " + (boxedA === boxedB))//true//值相等log(" boxedA == boxedB ? " + (boxedA == boxedB))//true// Int Int? Int?val a4: Int = 127boxedA = a4 boxedB = a4 log(" boxedA === boxedB ? " + (boxedA === boxedB))//true//值相等log(" boxedA == boxedB ? " + (boxedA == boxedB))//true// Int Int Intval a5: Int = 128val boxedA2: Int = a5 val boxedB2: Int = a5 log(" boxedA === boxedB ? " + (boxedA2 === boxedB2))//true//值相等log(" boxedA == boxedB ? " + (boxedA2 == boxedB2))//truexkj
xkj***n@gmail.com
love2kt
liu***jun@163.com
综上各位仁兄的理解,小弟发挥了一下想象力,假设有一堆货物(初始值)如果货物比较少(在[-128, 127] 之间。java里面就是自动装箱,可以理解为货物本身自带包装盒)那么把这些东西无论给甲还是给乙都不需要额外的箱子来装。所以甲乙手上的货物是一致的,二者相等。如果货物比较多([-128, 127]之外,多余一个包装盒。或者只多出一点,一个包装盒+一点散货)手拿不住了,需要拿箱子装了(装箱操作)那么甲需要一个箱子,乙需要一个箱子,手上的两个箱子是不同的(地址不同了)但是里面的货物还是一样的(值相等)
love2kt
liu***jun@163.com
ahwei
ahw***07@foxmail.com
参考地址