Kotlin:我可以用另一个函数覆盖一个函数吗? (如覆盖)

时间:2020-03-07 07:10:24

标签: kotlin

我是Kotlin的初学者。 我不确定我尝试的方式是否正确。 现在,我想覆盖并捕获变量

假设这是SOMETHING类的方法,可以重写:

fun whoAreYou() {}

这是我的功能:

fun thisFuntionsIs(): ()->Unit {
    var i = 0
    println("It's parent Function!")
    return { println("It's child Function! ${i++}") }
}

现在,我尝试用新功能覆盖现有功能:

fun whoAreYou() = thisFuntionsIs() // Suppose used the override keyword

现在,当我运行此功能时,它每次都会打印出“父”消息。

这不是我想要的。☹

如果whoAreYou是一个属性,而不是一个方法,那么我就可以使用它。

class SOMETHING {
    var whoAreYou = ()->{} // If it was a property...
    // fun whoAreYou() {} // But the current situation is
}
SOMETHING.whoAreYou = thisFuntionsIs()
SOMETHING.whoAreYou() // Yea~ I wanted that

有解决方案吗?还是我完全错了?请帮助我。

2 个答案:

答案 0 :(得分:2)

要进行覆盖,您需要创建父类和函数open,然后在扩展类中覆盖函数:

open class Parent {
    protected var counter = 0;
    open fun whoAreYou() = "It's parent Function!"
}

class Child : Parent() {
    override fun whoAreYou() = "It's child Function! ${counter++}"
}

fun main() {
    val parent: Parent = Parent()
    val child: Parent = Child()

    println(parent.whoAreYou()) // It's parent Function!
    println(child.whoAreYou()) // It's child Function! 0
    println(child.whoAreYou()) // It's child Function! 1
    println(child.whoAreYou()) // It's child Function! 2
}

答案 1 :(得分:0)

该代码有效。也许您只是误解了结果。稍作修改的版本:

fun main(args: Array<String>) {
    val x = SOMETHING()
    x.whoAreYou = thisFuntionsIs()
    x.whoAreYou()
    x.whoAreYou()
}

class SOMETHING {
    var whoAreYou = fun() {
        System.out.println("It's parent Function!")
    }
}

fun thisFuntionsIs(): () -> Unit {
    var i = 0
    System.out.println("It's Function!")
    return { System.out.println("It's lambda! ${i++}") }
}

输出:

>  It's Function!
>  It's lambda! 0
>  It's lambda! 1

x.whoAreYou = thisFuntionsIs()意味着thisFuntionsIs被调用,x.whoAreYouthisFuntionsIs分配给匿名函数返回。

相关问题