Eudy Contreras
Eudy Contreras

Reputation: 396

How to pass functional interface operation as parameter in Kotlin?

Given this functional interface in Java:

public interface Condition<T> {
   boolean check(T target);
}

The operation produce by that interface can be passed as parameter to the constructor of a class:

new ValidationRule<>(description,problem,target-> target.length() >= 2)

The third argument is a Condition interface where the operation to be perform is explicitly specified as:

target -> target.length() >= 2

I am having trouble duplicating this pattern in Kotlin. How can this be done in kotlin? Is there a kotlin specific way to do this.

PS I am new to Kotlin.

Upvotes: 2

Views: 553

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81588

Should be as simple as

typealias Condition<T> = (T) -> Boolean

class ValidationRule<T>(val description: T, val problem: T, val condition: Condition<T>) 

val validationRule = ValidationRule(description, problem, { target -> target.length() >= 2 }) 

Upvotes: 1

Related Questions