Search code examples
kotlinassertj

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


I'm using AssertJ in Kotlin and tried to use an AssertJ-Condition.

The constructor is defined like this:

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

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

But I can't get the creation right. I tried the following (and some more, which I omitted for brevity):

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

with this error: enter image description here

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

with this error: enter image description here

How can i succeed?


Solution

  • The best I can come up with is:

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

    Edit: Your code does not work because Kotlin lambda by default does not implement the required interface. If you run the following code:

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

    you get the following output:

    interface kotlin.jvm.functions.Function1
    
    interface java.util.function.Predicate
    

    The difference is obvious.