简体   繁体   中英

Lambda expressions “Not” predicate

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM