Kotlin有没有复制功能?

时间:2017-06-07 07:45:36

标签: kotlin

SELECT * FROM (SELECT SUM(c.[Chargeable Weight]) AS Sum, MAX (ts.systemstamp) AS Max, mm.MovementRef FROM dbo.whsConsignment wc INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference] inner join dbo.movMovement mm on mm.MovementID = m.MovementID --AND wc.whsHeaderID = wh.WhsHeaderID AND wc.StatusCode = 'NL' AND c.[Service Type] = 'C' --AND ts.SlackNoSlack like 'No Slack - Must Load%' --and ts.SLackNoSLack like 'No Slack - Tripped%' and ts.scheduledescription = 'No Slack - Tripped' group by mm.MovementRef) as chargeableweight --and ts.systemstamp = max (ts.systemstamp) Into #2chargns 是长度为n的列表,x为每个元素的值。

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

replicate(n:Int,x:T):List<T>

Kotlin中是否存在任何可重复的复制函数?

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

2 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:0)

如果您需要只读列表,可以通过以下方式实施getItem(position)

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") } 有多大,它都需要恒定的内存量。