首页 文章

Kotlin有复制功能吗?

提问于
浏览
2

replicate(n:Int,x:T):List<T> 是长度为n的列表,x为每个元素的值 .

我写了一个可变版本复制如下:

fun <T> mutableReplicate(n:Int, x:T) : MutableList<T>{
    val xs = mutableListOf<T>()
    for (i in 1..n){
        xs.add(x)
    }
    return xs
}

Kotlin中是否存在任何可重复的不可复制复制功能?

如何在Kotlin中为自己写一个不可变的复制函数?

2 回答

  • 6

    你可以使用 List instantiation functions . 它们接受从索引到所需元素的函数,但您也可以使用它们来创建常量值列表 .

    fun <T> replicate(n:Int,x:T):List<T> {
       return List(n) { x }
    }
    
  • 0

    如果您需要只读列表,可以通过以下方式实现 replicate

    fun <T> replicate(n: Int, x: T): List<T> = object : AbstractList<T>() {
        override val size: Int = n
        override fun get(index: Int): T = 
            if (index in 0..lastIndex) x else throw IndexOutOfBoundsException("$n")
    
    }
    

    它有一个优点,无论 n 有多大,它都需要恒定的内存量 .

相关问题