kotlin的基本功能

时间:2016-03-20 18:03:14

标签: 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()

}

1 个答案:

答案 0 :(得分:2)

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

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)
}