Peheje
Peheje

Reputation: 14214

Kotlin and parallelStream toArray

I think I'm getting sidetracked. I'm trying to utilize the Java parallelStream for performance reasons.

A function Specimen.pick() samples and returns an instance of Specimen. I want to parallize this with parallelStream when replacing pool.

var pool: Array<Specimen> = Array(100_000) .. 

This is what I'm trying to write in Kotlin:

pool = pool.asList().parallelStream().map { Specimen.pick(pool, wheel, r.split()) }.toArray(Specimen::new)

Which errors out on ::new

Instead I have to juggle back and forth between list and array:

pool = pool.asList().parallelStream().map { Specimen.pick(pool, wheel, r.split()) }.collect(Collectors.toList()).toTypedArray()

Which works, but seems resource wasteful rather than going directly to Array. If I let IntelliJ try to Kotlinize a Java example of this:

Java:

Person[] men = people.stream()
                      .filter(p -> p.getGender() == MALE)
                      .toArray(Person[]::new);

IntelliJ transformation:

val men = people.stream()
            .filter({ p -> p.getGender() === MALE })
            .toArray(Person[]::new  /* Currently unsupported in Kotlin */)

So maybe this is coming for Kotlin? Or is there another better way?

Upvotes: 3

Views: 3120

Answers (1)

JB Nizet
JB Nizet

Reputation: 691943

You can't use an array constructor reference, but every method reference can be expressed using a lambda expression:

.toArray<Person>({length -> arrayOfNulls(length)})

Upvotes: 9

Related Questions