Kotlin如何将嵌套List<People>映射为List<List<Student>>
嵌套列表映射实现方案
首先先修正你提供的普通List转换函数的小问题——在map的lambda中,this指代的是外层的List<People>,而非单个People实例,所以应该用it来访问单个对象的属性:
fun List<People>.convert(): List<Student> { return this.map { Student( age = it.age, name = it.name ) } }
嵌套列表的两种转换方式
方式一:复用已有扩展函数
对于List<List<People>>,只需要对外层列表再做一次map,每个内层列表直接调用上面定义的convert()方法即可:
fun List<List<People>>.convertNested(): List<List<Student>> { return this.map { innerList -> innerList.convert() } }
方式二:嵌套map直接转换
如果不想单独定义普通列表的扩展函数,也可以直接嵌套两层map一步完成转换:
fun List<List<People>>.convertNested(): List<List<Student>> { return this.map { innerList -> innerList.map { people -> Student( age = people.age, name = people.name ) } } }
使用示例
无论是哪种方式,调用起来都很简洁:
val peopleNestedList: List<List<People>> = // 你的嵌套People列表 val studentNestedList: List<List<Student>> = peopleNestedList.convertNested()
内容的提问来源于stack exchange,提问作者Jennie Cheng
相关产品推荐
相关产品推荐

