Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass a function as a parameter in Kotlin and print the returning value?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

you should write it as

print(::uppercase)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading