如何使用采用通用接口和其他参数的构造函数在 Kotlin 中创建对象

How to create an Object in Kotlin using a constructor which takes a generic interface and other parameters

我在 Kotlin 中使用 AssertJ 并尝试使用 AssertJ-Condition。

构造函数是这样定义的:

Condition(Predicate<T> predicate, String description, Object... args)

http://joel-costigliola.github.io/assertj/core-8/api/org/assertj/core/api/Condition.html

但是我无法正确创建。我尝试了以下(以及更多,为简洁起见我省略了):

Condition<File>({ it.name.startsWith("functional_questions") }, "Description")

出现此错误:

Condition<File>({ file -> file.name.startsWith("functional_questions") }, "Description")

出现此错误:

我怎样才能成功?

我能想到的最好的是:

Condition<File>(Predicate<File> { file -> file.name.startsWith("functional_questions") }, "description")

编辑:您的代码不起作用,因为默认情况下 Kotlin lambda 未实现所需的接口。如果您 运行 以下代码:

val predicate1 = { file: File -> file.name.startsWith("functional_questions") }
val predicate2 = Predicate<File> { file -> file.name.startsWith("functional_questions") }

predicate1::class.java.interfaces.forEach { println(it) }
println() //new line to separate outputs
predicate2::class.java.interfaces.forEach { println(it) }

你得到以下输出:

interface kotlin.jvm.functions.Function1

interface java.util.function.Predicate

区别很明显。

据我所知,AssertJ 没有对 Kotlin 的特殊支持,因此仅支持 Java Predicate。

在这里查看更多关于为什么我们不能将 kotlin lambda 作为功能接口传递的信息:

这里有两种实现方法:

@Test fun assertj() {
    Condition<File>(Predicate { it.name.startsWith("functional_questions") }, "Description")
    condition<File>("Description") { it.name.startsWith("functional_questions") }
}

fun <T> condition(description: String, predicate: (T) -> Boolean) =
    Condition<T>(Predicate<T> { predicate(it) }, description)

首先是显式谓词,其次是辅助函数。