gpt4 book ai didi

lambda - Kotlin:lambda 从不编译

转载 作者:行者123 更新时间:2023-12-01 19:37:12 25 4
gpt4 key购买 nike

我刚开始学习 Kotlin,我遇到了 lambdas 语法方面的问题。有一个小示例类:

class MathFunctions {
@FunctionalInterface
interface Operation {
fun calculate(a: Int, b: Int): Int
}

fun makeCalculations(a: Int, b: Int, operation: Operation): Int = operation.calculate(a, b)

companion object {
@JvmStatic
fun main(args: Array<String>) {
val plus = Operation { a, b -> a + b }
val mathFunctions = MathFunctions()
println(mathFunctions.makeCalculations(10, 20, plus))
}
}
}

该类永远不会编译,因为 lambda 有问题。 Java 中的相同内容如下所示:

public class MathFunctions {
@FunctionalInterface
interface Operation {
int calculate(int a, int b);
}

public int makeCalculations(int a, int b, Operation operation) {
return operation.calculate(a, b);
}

public static void main(String[] args) {
Operation plus = (a, b) -> a + b;
MathFunctions example = new MathFunctions();

System.out.println(example.makeCalculations(10, 20, plus));
}
}

应该纠正什么?我已经尝试在 Intellij Idea 中自动将 Java 转换为 Kotlin,但失败了。

最佳答案

您的代码的问题是 Kotlin does not allow SAM conversion to interfaces written in Kotlin .这个限制的原因是 Kotlin 有 functional types built into the language ,应该改用它们(或退回到 anonymous object expressions )。

您可以将代码重写为:

class MathFunctions {
fun makeCalculations(a: Int, b: Int, operation: (Int, Int) -> Int): Int =
operation(a, b)

companion object {
@JvmStatic
fun main(args: Array<String>) {
val plus: (Int, Int) -> Int = { a, b -> a + b }
val mathFunctions = MathFunctions()
println(mathFunctions.makeCalculations(10, 20, plus))
}
}
}

为了使代码更具可读性,可以使用type aliases :

typealias Operation = (Int, Int) -> Int

关于lambda - Kotlin:lambda 从不编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45979777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com