I am trying to map a list of objects to a list of objects of another type, then filter the list, then map to a list of a third type, just like I would do by chaining streams in Java 8+ (I changed the class and variable names to make it more meaningful but the structure is the same as in my code):
val results: List<AccountDto> = listOfPersons
.map { person -> getPersonAccount(person) }
.filter { account ->
if(validateAccount(account)){ // validateAccount is a function with boolean return type
// do something here like logging
return true
}
// do something else...
return false
}
.map { account ->
toDto(account) // returns an AccountDto
}
I get a compiler error on the return true
and return false
statements inside the filter lambda :
Error:(217, 32) Kotlin: The boolean literal does not conform to the expected type List<AccountDto>
If I use an anonymous function for the filter predicate it compiles fine :
.filter (fun(account):Boolean{
if(validateAccount(account)){
// do something here like logging
return true
}
// do something else...
return false
})
Why does the type inference fail in that case?
Is it possible to somehow I make it work with just a lambda ?