列出超类型的比方说,我有以下接口和类:添加亚型的名单在科特林
interface Attachable
class Image: Attachable
和下面的列表:
val attachableList = listOf<Attachable>(Image(),Image(),Image())
在这种情况下,我怎么可以添加attachables名单到图像列表?
var imageList = arrayListOf<Image>().addAll(attachableList)
// Error: Type mismatch. Required: Collection<Image>, Found: List<Attachable>
明显soultion是显式地映射它像:
val imageList = arrayListOf<Image>().apply{addAll(attachableList.map{it as Image})}
但我感兴趣的是在the article about variance in Kotlin
你应该关注'filterIsInstance'并且很快解释。它看起来是最好的和正确的方式来做到这一点。 – tynn