Creating new object Lambda


#1

Hi
i’m currently discovering Kotlin and struggling on trying to have this java code :

new Criteria().orOperator(aList.stream().map(date -> where(“KEY”).is(date)).toArray(Criteria[]::new));

converted in kotlin

here what i tried that deos not compile:

aList.stream().map { dateRange -> { Criteria.where(“KEY”).is(dateRange)}}.toArray(Criteria[]::new)

Thanks


#2

not sure but maybe something like Criteria().orOperator(aList.map { where(“KEY”).is(it) }.toArray())

Your problem is the lambda syntax { dateRange -> { Criteria.where(“KEY”).is(dateRange)}} => { dateRange -> Criteria.where(“KEY”).is(dateRange) } is enough


#3

val criteriaList = aList.stream().map { dateRange -> { Criteria.where(“KEY”).is(dateRange) } }.toList().toTypedArray()

Criteria().orOperator(*criteriaList)

Here i’m getting :

    Type mismatch.
    Required:
    Array<(out) Criteria!>!
    Found:
    Array<(() → Criteria!)!>

#4

You can use the same approach as the one used in toTypedArray() functions:

aList.stream()
	.map { dateRange -> Criteria.where("KEY").is(dateRange) }
	.toArray { size -> arrayOfNulls<Criteria>(size) } as Array<Criteria>

There is no need to create intermediate collections for that.

But to be honest it’s better to use idiomatic syntax :slight_smile::

aList.asSequence()
	.map { dateRange -> Criteria.where("KEY").is(dateRange) }
	.toTypedArray()

or:

aList.map { dateRange -> Criteria.where("KEY").is(dateRange) }.toTypedArray()

#5

Thanks