在kotlin中的基本功能

寻找一种方法来获得初等职能及其衍生工具我这样做:

abstract class Fun() { /** * i = 0 -- the function itself, * i = 1, 2, 3, ... -- its successive derivatives */ abstract fun d(i: Int, x: Float): Float } class Lin(val k: Float) : Fun() { // y = k*x override fun d(i: Int, x: Float, p: Float) = when (i) { 0 -> k * x 1 -> k else -> 0.0f } } class Sum(val fun0: Fun, val fun1: Fun) : Fun() { // y = fun0(x) + fun1(x) override fun d(i: Int, x: Float, p: Float) = fun0.d(i, x) + fun1.d(i, x) } class Example(val fun1: Fun, val fun2: Fun){ var res = fun1.d(0, 5.25f) // fun1 value at 5.25f res = fun1.d(1, 3.29f) // fun1 first derivative at 3.29f val sum = Sum(fun1, fun2) // sum of f1 and f2 res = sum(0, 3.78f) // sum value at 3.78f res = sum(1, 5.69f) // sum first derivative at 5.69f } 

Kotlin有没有更习惯的方法来做到这一点?

我已经公开了这个问题,就像我在Java中所做的那样,也就是包含函数的类。 我的问题是,如果我可以做同样的功能,把它们传递给一个类,如:

 class ParametricCurveXYZ(val fun_x: Fun, val fun_y: Fun, val fun_z: Fun) { fun pointToXYZ(s: Float) = VectorXYZ(fun_x.d(0, s), fun_y.d(0, s), fun_z.d(0, s)) fun tangent(s: Float) = VectorXYZ(fun_x.d(1, s), fun_y.d(1, s), fun_z.d(1, s)).normalized() } 

您可以使用lambdas而不是常规类和重载运算符来组合lambda表达式。

 fun lin(k: Float) = { i: Int, x: Float -> when (i) { 0 -> k * x 1 -> k else -> 0.0f } } operator fun ((Int, Float) -> Float).plus(that: (Int, Float) -> Float) = { i: Int, x: Float -> this(i, x) + that(i, x) } fun doSomething() { val sum = lin(1f) + lin(2f) val res = sum(0, 3.78f) }