```/** * Returns a new list of size [capacity] wi...
# codereview
m
Copy code
/**
 * Returns a new list of size [capacity] with elements from the original list, filled with [element] if needed
 */
fun <E> List<E>.fillWith(capacity: Int, element: E?): List<E?> {
    val outList = mutableListOf<E?>()
    repeat(capacity){ outList.add(element) }

    if(this.isEmpty()) return outList

    val sl = this.subList(0, min(capacity, this.size))

    sl.forEachIndexed { index, e ->
        outList[index] = e
    }
    return outList
}
w
Is it possible to you give some test cases?
Copy code
fun <T> List<T>.fillWith(capacity: Int, element: T?): List<T?> =
            when {
                size >= capacity -> this
                else -> this + List(capacity - size) { element }
            }

    @Test
    fun `given capacity less than the size when fill it should return original list`() {
        val l1 = listOf(1, 2, 3)
        val result = l1.fillWith(1, 0)
        assertEquals(listOf(1, 2, 3), result)
    }

    @Test
    fun `given capacity same as the size when fill it should return original list`() {
        val l1 = listOf(1, 2, 3)
        val result = l1.fillWith(3, 0)
        assertEquals(listOf(1, 2, 3), result)
    }

    @Test
    fun `given capacity more than the size when fill it should return list appended with element until the new capacity`() {
        val l1 = listOf(1, 2, 3)
        val result = l1.fillWith(5, 0)
        assertEquals(listOf(1, 2, 3, 0, 0), result)
    }
d
List(capacity) { this.getOrElse(it) { element } }
I think you're looking for a function called
padEnd
.
m
yes, padEnd will do. thank you!