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?
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.
You can use reference to the function ::
:
fun foo(s: String): Int = s.length
val bar = ::foo
And then invoke it:
bar("some string")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With