在科特林缩短筛选器和地图

时间:2018-11-06 06:51:45

标签: filter kotlin mapping

从包含用户的可空Transformation对象列表中,我想要非空用户的非空ID。有没有办法缩短这个表达?

val list: List<Transformation> = ...
list.filter {t -> t.user!!.id !== null }.map { t -> t.user!!.id!! }

2 个答案:

答案 0 :(得分:8)

您可以使用 System.Type type = typeof(UserPrefs); FieldInfo[] fields = type.GetFields(); foreach (var field in fields) { if (user != null) dbReference.Child("users").Child(user.UserId).Child(field.Name).SetValueAsync(field.GetValue(null)); else Debug.LogError("There is no user LoggedIn to write..."); }

mapNotNull

这将从列表中过滤掉所有list.mapNotNull { t -> t.user?.id } 个用户,以及null的ID(非空用户的ID)。

请注意,在这种情况下,您对null的使用不正确。它将导致您列表中!!的{​​{1}}个。您应该看看可空性运算符在Kotlin中的工作方式:https://kotlinlang.org/docs/reference/null-safety.html

答案 1 :(得分:2)

从您的示例代码中,尚不清楚列表中的内容。它不是接缝的用户列表,而是包含用户的事物列表。

给出

class User(val id: Int)

fun getIds(userList: List<User?>): List<Int> {
    return userList.filterNotNull().map { it.id }
}

或作为扩展功能:

fun List<User?>.getIds2() = filterNotNull().map { User::id }