I have this function:
fun uppercase(s: String) = s.uppercase()
And another function that can takes as a parameter a function as the one above:
fun print(uppercase: (s: String) -> String) {
print(uppercase("Ana"))
}
And in main I call:
print {
uppercase("Ana")
}
Why should I pass to the uppercase function the name twice? If I remove the argument in print function ("Ana"), I get an error. How to pass the String argument only once?
If I use:
print(uppercase) //I get StackOverflowError.
My goal is to pass a function that takes an argument of type String and returns the uppercase version and the print function and print the result. How can I solve this?
CodePudding user response:
you should write it as
print(::uppercase)
CodePudding user response:
// regular function definition
fun printMe(s:String): Unit{
println(s)
}
// higher-order function definition
fun higherfunc( str : String, myfunc: (String) -> Unit){
// invoke regular function using local name
myfunc(str)
}
fun main(args: Array<String>) {
// invoke higher-order function
higherfunc("Like this",::printMe)
}