Could someone please explain what it the key diffe...
# announcements
a
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
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
Damn, I just looked up the exact same link.
🐌 2
👍 2
a
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
No.
b
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
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
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
Copy code
@kotlin.internal.InlineOnly
public inline fun CharSequence.count(): Int {
    return length
}
k
Yes, that's the link I posted.