字符串
和 Java 一样,String 是不可变的。方括号 [] 语法可以很方便的获取字符串中的某个字符,也可以通过 for 循环来遍历:
for (c in str) {
println(c)}Kotlin 支持三个引号 """ 扩起来的字符串,支持多行字符串,比如:
fun main(args: Array<String>) {
val text = """
多行字符串
多行字符串
"""
println(text) // 输出有一些前置空格}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