List.fill or List.tabulate


#1

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.


#2

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


#3

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).


#4

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.


#5

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


#6

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.


#7

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


#8

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.


#9

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


#10

FYI this was added for lists in Kotlin 1.1:

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