https://kotlinlang.org logo
Title
c

CoopCoding

07/14/2019, 1:55 AM
Hi, I'm just starting to learn Kotlin and I'm a little confused by something. How come if I assign a function to a varibale, I am able to pass it in to map like this:
fun main() {
  val strings = listOf("Hello", "World", "!")
  val getLengthOfString = fun(str: String) : Int {
    return str.length
  }
  val lengths = strings.map(getLengthOfString)
  println(lengths)
}
But if the function is a regular function, I cant pass in the function name like so:
fun main() {
  val strings = listOf("Hello", "World", "!")
  fun getLengthOfString(str: String): Int {
    return str.length
  }
  val lengths = strings.map(getLengthOfString)
  println(lengths)
}
❤️ 2
l

leodeng

07/14/2019, 4:05 AM
you’ll need to use
::getLengthOfString
c

CoopCoding

07/14/2019, 4:15 AM
Ok, thanks.
b

b00m

07/14/2019, 4:42 AM
what does :: do here?
a
c

CoopCoding

07/14/2019, 5:48 AM
@Al Warren Thanks, I'm still a little fuzzy though. Is
::
basically used to satisfy the types? Also, in most other languages,
::
means bind, is that not the case here? Thanks.
s

Shawn

07/14/2019, 2:19 PM
::
isn’t an operator is used to specify function references. It looks a little weird since we’re referencing a function in the local scope. If you wanted to reference a method of a specific class it’d look like
Foo::bar
. Since the function exists within the local scope, there isn’t a name to really qualify its location by, so it comes out to just
::bar
.
::
is used probably because reusing
.
is ambiguous
c

CoopCoding

07/14/2019, 10:03 PM
Ah, got it, thanks. 🙂
👍 1
a

Al Warren

07/14/2019, 10:20 PM
Btw, the docs actually call it an operator. See the link above.
s

Shawn

07/14/2019, 10:24 PM
Apologies, I was imprecise in my wording, I meant more that
::
isn’t like bind or otherwise like
plus
or other infix operators - in this case it would fall in the same category as the dot operator or even
->
in C