gpt4 book ai didi

kotlin - Kotlin 函数真的是一流的类型吗?

转载 作者:行者123 更新时间:2023-12-04 22:39:30 28 4
gpt4 key购买 nike

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

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

有没有办法在不诉诸面向对象的情况下做到这一点?

最佳答案

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



不,它没有。

在 Kotlin 中,要将函数或属性作为值引用,您需要使用 callable references ,但它只是 obtaining a value 的一种语法形式的 function type :
fun foo(s: String): Int = s.length

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

一旦你获得了那个值(value),你就不受如何使用它的限制,这就是一流函数的意义所在。

关于kotlin - Kotlin 函数真的是一流的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54871235/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com