2

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.

3
  • did you read chapters "lambdas" and "higher order functions" in the docs? Commented Aug 19, 2018 at 8:43
  • @TimCastelijns yes I did but I still have trouble understanding the this pattern and the pattern specified in that documentation can be used in similar ways! Maybe I just failed to understand Commented Aug 19, 2018 at 8:46
  • 3
    There are plenty of examples showing the syntax here: kotlinlang.org/docs/reference/lambdas.html. Have you at least tried anything? What? Commented Aug 19, 2018 at 9:18

1 Answer 1

1

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 }) 
Sign up to request clarification or add additional context in comments.

3 Comments

If the interface already exists in Java, then you don't need the typealias.
Thanks for the answer! The problem is not translating from one syntax to the other the problem is that the parameter wont accept the lambda expression as an argument.
You might need to specify the , problem, Condition<SomeType> { target ->

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.