2017-07-02 39 views
1

列出超類型的比方說,我有以下接口和類:添加亞型的名單在科特林

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

回答

6

問題描述的soultion是imageList可能只包含類型的實例Image。但是,attachableList包含Attachable類型的實例。由於除Image之外的其他類可能實現Attachable,因此無法安全地將所有元素從attachableList添加到imageList

如果您確信attachableList只包含Image類型的實例,使用it as Image是罰款(雖然有也.filterIsInstance<Image>(),我不使用方差的特徵看的方式解決這個問題。

+0

你應該關注'filterIsInstance'並且很快解釋。它看起來是最好的和正確的方式來做到這一點。 – tynn

3

你只能說imageList.addAll(attachableList as List<Image>)如果你確信attachableList將只包含圖像。

,您會收到一個未經檢查的投警告,但沒有編譯器錯誤。

val attachableList: List<Attachable> = listOf(Image(), Image()) 
var imageList = arrayListOf<Image>() 
imageList.addAll(attachableList as List<Image>) 
println(attachableList) 
println(imageList) 
println(imageList == attachableList)