Reputation: 135
I currently on my way to learn Kotlin and hopefully becoming a developer but I am stuck on a problem and can not figure out the answer (even after extensive google research).
It would be much appreciated if somebody could help me and explain their solution. :)
Thank you in advance!
Question:
"Write a predicate that takes the originalPredicate: (Char) -> Boolean variable and returns the negated result. Your predicate is to filter a string."
Implementation: val notPredicate: (Char) -> Boolean = TODO("Provide implementation")
Upvotes: 2
Views: 544
Reputation: 8106
So, let's understand the problem first.
You have given originalPredicate: (Char) -> Boolean
, so it will return a Boolean value according to the character. For example, if it will return true for 'a', 'c', 'e', etc. (just an example), then you have to return false for them and true for 'b', 'd', 'f', etc.
So, you wanna call the originalPredicate
, know the result (i.e. true or false) and then inverse the result and then return it.
val notPredicate: (Char) -> Boolean = { char ->
val booleanValue = originalPredicate(char)
return@notPredicate !booleanValue
}
If you simplify the steps, and use it
which is default name of variable inside lambda, and since last statement in the lambda is returned by itself (so you don't have to write explicit return) :
val notPredicate: (Char) -> Boolean = { !originalPredicate(it) }
Upvotes: 4
Reputation: 195229
Do you mean this:
val originalPred :(Char) -> Boolean = {it>'a'}
val somePred :(Char) -> Boolean = {!originalPred.invoke(it)}
Note, the it>'a'
is just an example.
Upvotes: 0