kotlin - 如何在没有类声明的情况下将当前实例传递给另一个类的构造函数?
问题描述
我有一项服务会返回一个实体列表,例如:
data class TypeDto(
val type: Type,
val stages: List<StageDto>)
在应用了几个filter
和flatMap
操作后,我得到了具有以下结构的所需数据:
data class CustomerDto(
val id: String,
val name: String)
为了提取过滤和映射的逻辑,我创建了一个作为构造函数参数并执行所有集合操作的CustomerDtoWrapper
类。List<TypeDto>
所以,最后它看起来如下:
val types = service.getTypes()
val customers = CustomerDtoWrapper(types).filteredCustomers()
但我想让它更流畅,更易于阅读。是否可以在 之后调用某个函数getTypes()
,所以它types
的CustomerDtoWrapper
类型如下:
val types = service.getTypes().someFun { ... }
val customers = types.filteredCustomers()
解决方案
您可以为此编写例如扩展函数:
fun List<TypeDto>.toFilteredCustomers() = CustomerDtoWrapper(this).filteredCustomers()
并像这样使用它:
val customers = service.getTypes().toFilteredCustomers()
推荐阅读
- javascript - Openlayers:TypeError:t.getType 不是函数
- c - 如何收集用户定义的 pthread 退出状态
- platformio - PlatformIO:[upload] Error 2 with esp8266 ESP-07 board
- reactjs - React infinite update loop with useCallback (react-hooks/exhaustive-deps)
- javascript - AngularJS controller prepended by a ? In Chrome
- javascript - How to set current directory for ES6 dynamic import function
- json - 如何对来自 API 的数据进行分页
- java - 在 Java 中动态命名类实例
- python - AttributeError:“NoneType”对象没有属性“文本”。确实使用 Python 进行网页抓取
- python - python:如何在返回 posix.statvfs_result 数据类型时模拟 os.statvfs