Answer the question
In order to leave comments, you need to log in
Kotlin collections: Why doesn't the function call in .map work?
How to pass a static class method(Basically doesn't matter, any method) tocollection.map()
class Utils {
companion object {
fun squareOf(x:Int) = x * x
}
}
fun main(args: Array<String>) {
val a = listOf(1, 2, 3, 5, 10)
val b = a.map(Utils.squareOf)
for(x in a) print("$x ")
println("");
for(x in b) print("$x ")
println("");
}
val b = a.map(Utils.squareOf)
не работает. Я могу сделать так: val b = a.map { Utils.squareOf(it) }
, но должно работать и в первом случае.Answer the question
In order to leave comments, you need to log in
First, not "does not work", but "does not compile". Secondly, you wrote a syntactically incorrect construction. This is not a function call, you cannot write it in this place. You can only lambda or function reference.
You can write it like this: .map(Utils.Companion::squareOf)
Thirdly, you don't need to drag a bad Java model into Kotlin, where "everything is a class". This Utils class is of no use. You just need to write a function
fun squareOf(x:Int) = x * x //in the Utils.kt file
and then use a reference to it:
.map(::squareOf)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question