https://kotlinlang.org logo
Title
c

Chris Cordero

04/11/2020, 9:37 PM
I've got a
List<Int>
that I want to map over and do some calculations on. Since I'm learning Kotlin, I thought I'd try to do it two ways. This one works:
val foo: List<Int> = listOf(100, 200, 300)
foo.map { it / 3 - 2 } .forEach { println(it) }
However, I wanted to see what to do if I wanted to make a reusable transform function inside the
map
. So I tried this:
fun myMapFunc(it: Int): Int {
    return it / 3 - 2
}

val foo: List<Int> = listOf(100, 200, 300)
foo.map(myMapFunc).forEach { println(it) } // error
I already know I can fix it by doing this:
foo.map { myMapFunc(it) }
But I feel like the first way should work too... Why doesn't it?
s

Shawn

04/11/2020, 9:49 PM
it’s because unlike python and similar other languages, function references must be deliberately qualified in order to be passed as an argument or assigned to a variable
try
foo.map(::myMapFunc)
c

Chris Cordero

04/11/2020, 9:50 PM
That works
Some follow up questions: 1. What do you mean by "deliberately qualified"? 2. What is the
::
doing?
I can see here: https://kotlinlang.org/docs/reference/keyword-reference.html#operators-and-special-symbols That the
::
means that it is "creating a member reference or class reference", but I'm not sure what that means here exactly.
s

Shawn

04/11/2020, 9:55 PM
So the way symbols work in Kotlin is kinda sorta similar to how it’s done in Java, which doesn’t treat methods or classes as first-class tokens
if you want to pass in data about a class’s type to a function, you can’t just use the class’s name, like
foo(Bar)
you can pass in
foo(Bar::class)
which will generate a
KClass<Bar>
for you and send that to the function
i.e. a class reference
this isn’t just to mirror how Java does things — using a class name without
::
will actually let you reference a class’s
companion object
if one is defined on it
as for the member reference bit, technically speaking, Kotlin allows you to represent a reference to any member of a given class (or top-level declarations in a Kotlin file, which technically compiles to a class on the JVM anyhow)
references to variables aren’t supported yet, but you can reference method/functions as well as properties (variables that are class members and have accessors generated for them) just fine (you really should just have a read of this whole page https://kotlinlang.org/docs/reference/reflection.html)
in a very loose, imperfect sense
::
is kinda like using
*
to get a pointer to something in C/C++
(this also has some implications for representing references to constructors but I won’t go down that path unless you ask lol)
c

Chris Cordero

04/11/2020, 10:04 PM
lol that was a great explanation thank you very much for the detailed answer
👍 2
No worries on the constructor thing, I’ve got enough to let marinade in my head
👌 1