6

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

Ashwin
  • 12,691
  • 31
  • 118
  • 190

1 Answers1

16

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.

Salem
  • 13,516
  • 4
  • 51
  • 70