首页 > 解决方案 > 如何在没有类声明的情况下将当前实例传递给另一个类的构造函数?

问题描述

我有一项服务会返回一个实体列表,例如:

data class TypeDto(
        val type: Type,
        val stages: List<StageDto>)

在应用了几个filterflatMap操作后,我得到了具有以下结构的所需数据:

data class CustomerDto(
        val id: String,
        val name: String)

为了提取过滤和映射的逻辑,我创建了一个作为构造函数参数并执行所有集合操作的CustomerDtoWrapper类。List<TypeDto>所以,最后它看起来如下:

val types = service.getTypes()
val customers = CustomerDtoWrapper(types).filteredCustomers()

但我想让它更流畅,更易于阅读。是否可以在 之后调用某个函数getTypes(),所以它typesCustomerDtoWrapper类型如下:

val types = service.getTypes().someFun { ... }
val customers = types.filteredCustomers()

标签: kotlincollections

解决方案


您可以为此编写例如扩展函数:

fun List<TypeDto>.toFilteredCustomers() = CustomerDtoWrapper(this).filteredCustomers()

并像这样使用它:

val customers = service.getTypes().toFilteredCustomers()

推荐阅读