不修改原类的前提下扩展功能,让代码更简洁可读。
为已有类添加新方法,无需继承或修改原类。
fun String.removeSpaces(): String = replace(" ", "") val s = "Kotlin Lang" println(s.removeSpaces()) // KotlinLang
为类添加计算属性,不占用额外存储。
val String.lastChar: Char get() = get(length - 1)