https://kotlinlang.org logo
#getting-started
Title
# getting-started
o

oday

07/14/2021, 9:30 AM
is this python code not equivalent to this Kotlin code?
Copy code
val leftOne = arrayOne.drop(0).filter { it < arrayOne.first() }.toIntArray()
I guess that drop needs to be drop(1), but is there a neater way?
I guess
drop(arrayone.first())
would be neater
u

Ubi

07/14/2021, 11:34 AM
drop(arrayone.first())
will be incorrect.
drop(n)
removes first n elements from the array.
drop(1)
is correct in your case. See: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/drop.html
t

Tobias Berger

07/14/2021, 11:52 AM
When using
drop(1)
the result should be identical to your python code, although the code flow is a bit different. using drop and filter will create List instances, so if performance is crucial, you might benefit from converting to a sequence before these operations and back to a list later. Also, in Kotlin, especially when working with JVM, Lists are far more common than arrays. If you want a neater way, I suggest refactoring and not using the first array item for the comparison. Just have one parameter for the reference value and another for the items you want to filter. Of course I don't know your specific use case and if there is anything really blocking you from doing that.
so assuming you have an array without the reference value, you could just do
Copy code
array.filter { it < referenceValue }.toIntArray()
or just work with Lists and omit the
toIntArray()
call
o

oday

07/14/2021, 1:45 PM
what im doing here is copying an algorithms as is
im trying to stay as close to the metal as possible, getSmaller() is a part of it only
when I get that working , I can make it more idiomatic
d

Dave K

07/14/2021, 2:05 PM
First is never smaller than itself so you could also just drop the drop entirely. If you want a bound variable for the reference value you could use the run extension?
array.first().run { array.filter { it < this }.toIntArray() }
I’m not sure where the sweet spot for you is in terms of keeping it as close to the metal as possible while also being neater
4 Views