扩展函数
fun String.lettersCount():Int{var count = 0for(i in this){if(i.isLetter())count++}return count
}
fun main(){val str:String = "12we"println(str.lettersCount())
}
相当于直接将方法写在类里面。函数体内可以直接使用this而不用传参。
运算符重载
class Money(var yuan:Int,var fen:Int){operator fun plus(money: Money): Money {return Money(yuan+money.yuan,fen+money.fen)}operator fun plus(Yuan:Int):Money {return Money(yuan+Yuan,fen)}
}fun main(){var money:Money = Money(1,1)var money2:Money = Money(2,2)println((money2+money).yuan)println((money2+money).fen)println((money2+1).yuan)
}
operator和plus是不能变的,plus表示“+”