假設我們有一個像這樣的擴展函式
fun <T> MutableList<T>.fillWith(default: T, size: Int) = apply {
if (this is ArrayList) {
ensureCapacity(size)
}
while (size < newSize) add(default)
}
我們的目標是能夠用默認值填充任何串列T,但回傳this以便我們可以繼續鏈接其他方法,或者只是將其分配給這樣的一個運算式中的欄位val data = LinkedList<String>().fillWith("", 42)
不幸的是,我們的回傳型別不出所料是MutableList有辦法回傳實際的最具體的型別嗎?這樣我就可以定義一個通用的擴展函式,但能夠做類似的事情
val data1 : LinkedList<String> = LinkedList().fillWith("", 42)
val data2 : ArrayList<String> = LinkedList().fillWith("", 42)
uj5u.com熱心網友回復:
正如@Pawel 所建議的,您可以在串列型別本身中使函式通用:
fun <R, T: MutableList<R>> T.fillWith(default: R, newSize: Int) : T = apply {
if (this is ArrayList<*>) {
ensureCapacity(size)
}
while (size < newSize) add(default)
}
然后,您必須在建構式呼叫的呼叫站點上指定串列中元素的型別,因為編譯器無法推斷它:
val data1 = LinkedList<String>().fillWith("", 42)
val data2 = ArrayList<String>().fillWith("", 42)
請注意,您也可以簡單地使您的函式回傳Unit并apply在呼叫站點上使用。
此外,如果您不太關心特定的串列實作,那么已經有內置函式List()和MutableList()用于初始化的特定用例,如下所示:
// creates a list of 42 empty strings
val list = MutableList(42) { "" }
// creates a list of 42 strings "elt 0", "elt 1" etc.
val list = MutableList(42) { index -> "elt $index" }
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363419.html
上一篇:獲取泛型替換型別
