Are Kotlin functions really first class types?
Asked Answered
G

2

5

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?

Gandzha answered 25/2, 2019 at 17:4 Comment(0)
S
7

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.

Strappado answered 25/2, 2019 at 17:12 Comment(1)
What about static methods in Java, e.g. Files.IsDirectory? I can't seem to get this to work in the same way.Gandzha
S
4

You can use reference to the function :::

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

val bar = ::foo

And then invoke it:

bar("some string")
Saintpierre answered 25/2, 2019 at 17:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.