在kotlin函数中获取映射和收集器错误



我正在尝试将这个java函数转换为kotlin。

List<Long> creatorIds = polls.stream()
.map(Poll::getCreatedBy)
.distinct()
.collect(Collectors.toList());
List<User> creators = userRepository.findByIdIn(creatorIds);
Map<Long, User> creatorMap = creators.stream()
.collect(Collectors.toMap(User::getId, Function.identity()));
return creatorMap;
}

我以以下内容结束:

fun getPollCreatorMap(polls: List<Poll>): Map<Long?, User?>? {
// Get Poll Creator details of the given list of polls
val creatorIds: List<Long?> = polls.stream().collect(Collectors.toList())
.map(Poll::getCreatedBy).distinct()
val creators: List<User?>? = userRepository!!.findByIdIn(creatorIds)
val creatorMap: Map<Long?, User?> = creators!!.stream()
.collect(Collectors.toMap(User::getId, Function.identity()))
return creatorMap
}

然而在这一行

.collect(Collectors.toMap(User::getId, Function.identity()))

我得到以下错误:

Type mismatch.
Required:
((User?) → Long?)!
Found:
KFunction1<User, Long?>

在kotlin中不需要stream()。kotlin中的集合类提供了您需要的所有方法。(例如map, distinct, toMap)。下面是编写函数的kotlin方法:

fun getPollCreatorMap(polls: List<Poll>): Map<Long?, User?>? = polls.map{it.createdBy}.distinct().let{ creatorIds ->
userRepository?.findByIdIn(creatorIds)?.map{
Pair(it.id,it)
}.toMap()
}

我不知道你的数据的可空性,所以我只是让它们都为空。如果您知道可空性,则应该尝试使代码尽可能精确。

最新更新