Chris Cordero
04/11/2020, 9:37 PMList<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?Shawn
04/11/2020, 9:49 PMfoo.map(::myMapFunc)
Chris Cordero
04/11/2020, 9:50 PM::
doing?::
means that it is "creating a member reference or class reference", but I'm not sure what that means here exactly.Shawn
04/11/2020, 9:55 PMfoo(Bar)
foo(Bar::class)
which will generate a KClass<Bar>
for you and send that to the function::
will actually let you reference a class’s companion object
if one is defined on it::
is kinda like using *
to get a pointer to something in C/C++Chris Cordero
04/11/2020, 10:04 PM