Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Kotlin functions really first class types?

Does the fact that this doesn't compile mean that they're not quite first class types?

fun foo(s: String): Int = s.length
// This won't compile.
val bar = foo

Is there a way to do this without resorting to OO?

like image 310
F. P. Freely Avatar asked Dec 24 '22 00:12

F. P. Freely


2 Answers

Does the fact that this doesn't compile mean that they're not quite first class types?

No, it doesn't.

In Kotlin, to reference a function or a property as a value, you need to use callable references, but it is just a syntax form for obtaining a value of a function type:

fun foo(s: String): Int = s.length

val bar = ::foo // `bar` now contains a value of a function type `(String) -> Int`

Once you get that value, you are not limited in how you work with it, which is what first-class functions are about.

like image 189
hotkey Avatar answered Jan 15 '23 20:01

hotkey


You can use reference to the function :::

fun foo(s: String): Int = s.length

val bar = ::foo

And then invoke it:

bar("some string")
like image 29
Sergey Avatar answered Jan 15 '23 20:01

Sergey