List.fill or List.tabulate

Is there a Kotlin equivalent of this scala code:

List.fill(10)(Random.nextInt())

I want to create a List, of size n, where each element is generated by a function.

One option is to use the array constructor: IntArray(10) { Random().nextInt() }.asList()

That’s great.

What about adding something that takes a function int => T, where int is the number in the tabulation. That would be handy (that’s scala’s List.tabulate).

Generally speaking, we’re not adding everything that might come in handy to the standard library. The size of the standard library is a major concern for Android developers, and so we prefer to add only functions which support relatively common programming patterns.

You can also do: (1..10).map { Random().nextInt() }. Or use the index passed to the lambda: (1..10).map { i -> Random().nextInt(i) }

1 Like

I like this approach. Sooner or later something like Guava or Apache Commons will appear for Kotlin where all the nice “helper” methods have their home.

Yes, I can do that, but its horrible :slight_smile:

Looks like I’ll have to start one for all the methods I will want to bring across from Scala. It’s good being able to do the extension methods easily.

I haven’t checked for IntArray, but Array<T> general will provide the index of the item to the Initialiser closure. It’s type is (Int)->T

FYI this was added for lists in Kotlin 1.1:

https://kotlinlang.org/docs/reference/whatsnew11.html#array-like-list-instantiation-functions

1 Like