//重写 成员函数的扩展函数//如果你希望子类可以重写 父类的扩展函数 应该用open 去修饰扩展函数interface Base{
}
class Electron : Base{
}
class Particle : Base{
}
openclass Element(val name: String){
openfun Particle.react(name: String): Unit{
println("$name is reacting with a particle")
}
openfun Electron.react(name: String): Unit{
println("$name is reacting with an electron to make an isotope")
}
fun react(particle: Particle): Unit{
particle.react(name)
}
}
class NobleGas(name: String): Element(name){
overridefun Particle.react(name: String):Unit{
println("$name is noble, it does not react with particles")
}
overridefun Electron.react(name: String): Unit{
println("$name is noble it does not react with electrons")
}
fun react(particle: Electron): Unit{
particle.react(name)
}
}
fun main(args: Array<String>){
val selenium = Element("Selenium")
selenium.react(Particle())
//selenium.react(Electron())//书上这个例子几把 不会写
}
//协同对象 也可以实现扩展函数 协同对象就是工具类 调用它的是对象本身 不是对象的实例fun Int.Companion.random():Int{
val random = Random()
return random.nextInt()
}
//我们可以调用这个扩展函数 不需要 Companion 关键词fun testCompainExtensionFun(){
val int = Int.random()
}
//函数返回多个值fun roots3(k: Int):Pair<Double, Double>{
require(k >= 0)
val root = Math.sqrt(k.toDouble())
return Pair(root, -root)
}
fun testMulitReturnFun(){
val (pos,neg) = roots3(16)
}
//Infix 函数fun testInfixFun1(){
val pair = "LonDon"to"UK"//to 创建一个Pari实例
}
//成员函数被Infix 定义,可以换成一种写法 实例 函数名称 参数//例如下面的例子class Account{
var balance = 0.0fun add(amount: Double): Unit{
this.balance = balance +amount
}
}
fun testAccount(){
val account = Account()
account.add(100.00)
}
class InfixAccount{
var balance = 0.0
infix fun add(amount: Double): Unit{
this.balance = balance +amount
}
}
fun testInfixAccount(){
val account2 = InfixAccount()
account2 add 110.00// 实例名 函数名 参数val pair1 = Pair("london","pairs")//这两种写法是一样的val pair2 = "london"to"paris"
}
//重写 成员函数的扩展函数//如果你希望子类可以重写 父类的扩展函数 应该用open 去修饰扩展函数interface Base{}class Electron : Base{}class Particle : Base{}open class Element(val name: String){ open fun Particle.react(name: String): Un