实现具有参数化功能的接口

时间:2016-06-29 16:48:58

标签: kotlin

假设我有一个界面

A

我想在课程B(例如)中实施calculation,以便在B的构造函数中提供class B (f : (Int) -> Int) : A { override fun calculate(n: Int): Int //...somehow assign f to calculate } ,类似的东西:

f

这可以在不B interface A { val calculate: (n: Int) -> Int } class B(f: (Int) -> Int) : A { override val calculate = f } 属性的情况下完成吗?

嗯......这有效:

fun

有人可以在此解释val$result= mysqli_query($conn, "SELECT name, trans_id, amount FROM bustomer"); 之间的预期语法差异吗?我知道Function definition: fun vs val但希望获得语言水平'理解。

2 个答案:

答案 0 :(得分:3)

实现这一目标的最简单方法是:

class B(val f : (Int) -> Int) : A {
    override fun calculate(n: Int): Int = f(n)
}

答案 1 :(得分:1)

是的,可以在不f属性B的情况下完成此操作。例如将class delegation用于object expression

class B(f: (Int) -> Int) : A by object : A {
    override fun calculate(n: Int) = f(n)
}

即便如此,private val似乎更适合这个简单的例子。