Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to reduce a list of booleans in kotlin

I am trying to map to boolean and reduce in kotlin. This is my code

class Model{
 fun isEmpty() : Boolean
}


list.asSequence().map { model ->
      {
        model.isEmpty()
      }
     }.reduce { acc, next -> (acc && next)}

But compiler gives me an error telling

Type mismatch required () Boolean? but found Boolean

What am I doing wrong? I hope I am not doing anything conceptually wrong

like image 387
Ashwin Avatar asked Aug 24 '17 12:08

Ashwin


1 Answers

This isn't Kotlin's lambda syntax.

Kotlin lambdas are entirely contained within {}, i.e.:

{
    arg1, ..., argn ->
    [ lambda body ]
    [ last statement (implicitly returned) ]
}

By doing

list.asSequence().map { model ->
    {
        model.isEmpty()
    }
}

You are making a lambda that returns another lambda of type () -> Boolean:

{
    model.isEmpty()
}

So the real type of this lambda is (Model) -> () -> Boolean.

Remove the inner brackets:

list.asSequence().map { model -> model.isEmpty() }.reduce { acc, next -> acc && next }

Additionally, single-parameter lambdas have an implicit parameter name it, so you could just write:

list.asSequence().map { it.isEmpty() }.reduce { acc, next -> acc && next }

Also, it looks like you're trying to check if an entire list is empty. I believe you can simply write:

list.all { it.isEmpty() }

or use a method reference:

list.all(Model::isEmpty)

though that's up to personal preference.

like image 99
Salem Avatar answered Sep 24 '22 13:09

Salem