【发布时间】:2018-12-16 13:46:38
【问题描述】:
我正在尝试将对象列表映射到另一种类型的对象列表,然后过滤列表,然后映射到第三种类型的列表,就像我在 Java 8+ 中链接流所做的那样(我更改了类和变量名称以使其更有意义,但结构与我的代码相同):
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
}
过滤器 lambda 中的 return true 和 return false 语句出现编译器错误:
Error:(217, 32) Kotlin: The boolean literal does not conform to the expected type List<AccountDto>
如果我对过滤谓词使用匿名函数,它编译得很好:
.filter (fun(account):Boolean{
if(validateAccount(account)){
// do something here like logging
return true
}
// do something else...
return false
})
为什么在这种情况下类型推断会失败?
是否有可能以某种方式使其仅使用 lambda 工作?
【问题讨论】:
标签: functional-programming kotlin java-stream