扩展函数重写,返回多参函数,infix函数

//重写 成员函数的扩展函数
//如果你希望子类可以重写 父类的扩展函数 应该用open 去修饰扩展函数
interface Base{

}
class Electron : Base{

}
class Particle : Base{

}
open class Element(val name: String){
    open fun Particle.react(name: String): Unit{
        println("$name is reacting with a particle")
    }
    open fun 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){
    override fun Particle.react(name: String):Unit{
        println("$name is noble, it does not react with particles")
    }

    override fun 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.0
    fun 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"
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值