列出超類型的比方說,我有以下接口和類:添加亞型的名單在科特林
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