Kotlin功能真的是一流的吗?

F. *_*ely 4 first-class-functions kotlin

这不编译的事实是否意味着他们不是一流的类型?

fun foo(s: String): Int = s.length
// This won't compile.
val bar = foo
Run Code Online (Sandbox Code Playgroud)

有没有办法在不诉诸OO的情况下做到这一点?

hot*_*key 6

这不编译的事实是否意味着他们不是一流的类型?

不,它没有.

在Kotlin中,要将函数或属性作为值引用,您需要使用可调用引用,但它只是用于获取函数类型的语法形式:

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

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

一旦你获得了这个价值,你就不会受限于你如何使用它,这就是一流的功能.


Ser*_*gey 4

您可以使用该函数的引用 ::

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

val bar = ::foo
Run Code Online (Sandbox Code Playgroud)

然后调用它:

bar("some string")
Run Code Online (Sandbox Code Playgroud)