QED
QED

Reputation: 9923

Initialize Array of non-optionals without using constructor

I am using an Array of non-optional values, and I want them to stay non-optional, but I can't use Array's default constructor because of problems described here.

Furthermore, the .also{} trick described in the linked won't work for me, because mine is not an array of some primitive type with its own special WhateverArray class.

Is there some Kotlin trick by which I can initialize my a below? Or must I resort to building some list and then converting it?

// please assume Stream<MyNonprimitiveType> magically gives me
// size() -> Int and
// next() -> MyNonprimitiveType
val stream : Stream<MyNonprimitiveType> = Stream<MyNonprimitiveType>()
val size : Int = stream.size()
val a : Array<MyNonprimitiveType> = ??? // use stream.next()

Upvotes: 0

Views: 99

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

Here's a complete example doing what you want, without using a temporary list:

class Stream<T>(private val list: List<T>) {
    val size = list.size;
    private val it = list.iterator()

    fun next(): T {
        return it.next()
    }
}

inline fun <reified T: Any> Stream<T>.toArray(): Array<T> {
    val tmp: Array<T?> = arrayOfNulls(size)
    for (i in 0 until size) {
        tmp[i] = next()
    }
    return tmp as Array<T>
}

fun main() {
    val stream : Stream<String> = Stream(listOf("a", "b"))
    val a: Array<String> = stream.toArray()

    println(Arrays.toString(a))
}

Upvotes: 2

Related Questions