https://kotlinlang.org logo
#announcements
Title
# announcements
a

Anthony Styzhin

11/24/2019, 5:33 PM
Could someone please explain what it the key difference between these two options of the same function?
fun findShort(s: String): Int = s.split(" ").minBy { it.length }!!.count()
vs
fun findShort(s: String): Int = s.split(" ").minBy { it.length }!!.length
Both options work, pass unit tests and both are presented among solutions at codewars. Just trying to satisfy my curiosity ^^ Thanks in advance!
k

karelpeeters

11/24/2019, 6:16 PM
Both
count
and
length
are on
String
here, so everything else is not relevant. Then
count
is defined here: https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Strings.kt#L946-L952 So they're exactly the same.
👍 2
b

Burkhard

11/24/2019, 6:18 PM
Damn, I just looked up the exact same link.
🐌 2
👍 2
a

Anthony Styzhin

11/24/2019, 6:20 PM
Thanks a lot. So in case of a string there’s no difference in something like one is O(n) and the other O(1)?
k

karelpeeters

11/24/2019, 6:20 PM
No.
b

Burkhard

11/24/2019, 6:23 PM
My guess the
count
function is just there to be more similar to
Collection
(might actually be
Iterable
). It also has
count
and
length
, but in this case I think
length
calls
count
and not the other way round.
k

karelpeeters

11/24/2019, 6:25 PM
No for collection
count
returns
size
which is part of the
Collection
interface.
Iterable
also has
count
but that is
O(n)
.
🙏 1
👍 1
b

Burkhard

11/24/2019, 6:32 PM
Woops your right, either way,
length
and
count
are the same for all classes/interfaces in the standard library (unless someone can point me to an exception).
j

John

11/25/2019, 11:37 AM
Copy code
@kotlin.internal.InlineOnly
public inline fun CharSequence.count(): Int {
    return length
}
k

karelpeeters

11/25/2019, 11:37 AM
Yes, that's the link I posted.
8 Views