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?
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")
© 2022 - 2024 — McMap. All rights reserved.
Files.IsDirectory
? I can't seem to get this to work in the same way. – Gandzha