Kotlin docs stated that it supports higher-order functions. Why would the language even need a ::function syntax when passing a top level function as an argument?

Given:

fun isOdd(x: Int) = x % 2 != 0
val numbers = listOf(1, 2, 3)
println(numbers.filter(::isOdd)) // here.

为什么不

fun isOdd(x: Int) = x % 2 != 0
val numbers = listOf(1, 2, 3)
println(numbers.filter(isOdd)) // simple and makes more sense

更多关于function reference syntax here的信息.

推荐答案

Kotlin language design tries to avoid ambiguous situations where some absence of something could be both correct and incorrect syntax at the same time. For example if you allowed the proposed syntax:

isOdd     // error, function invocation expected isOdd(...)
isOdd     // not error, you have a function reference

The :: is a clear signal as to the intent. Because of this, you get only an error in the isOdd case because you now have possibilities that do not overlap:

isOdd      // error, function invocation expected isOdd(...)
::isOdd    // function reference
isOdd()    // error, missing parameter x
isOdd(x)   // function call

This is why Kotlin avoids things that lead to ambiguous states. Your eyes can also quickly pick up the problem, just as the IDE and static analysis can, just as the compiler does. If you start allowing this looser syntax you will start running into compounded ambiguities such as when using as infix functions and so on. Language design is more complicated than "oh, let's make them type less characters" because the complexity matrix is much larger than you imagine if you only look at one use case ignoring all the others.

Kotlin相关问答推荐

当通过firstOrders访问时,存储在伴随对象中的对象列表具有空值

我可以检测一个函数是否在Kotlin中被递归调用(即,重入)吗?

将文本与文本字段的内容对齐

如果启用了Flyway迁移,则不能具有配置属性';datources.default.架构-生成

Kotlin中一个接口的实现问题

限制通用Kotlin枚举为特定类型

Kotlin 协程:flatMapLatest 什么都不发出

JavaFX - 你如何在 Kotlin 中使用 MapValueFactory?

Kotlin:不允许在辅助构造函数参数上使用val

Kotlin 语言是如何用 Kotlin 编写的?

变量后的Android问号

在用Kotlin编写的Android库公共API中处理R8+JvmStatic Annotation+Lambda

Kotlin:sealed class cannot "contain" data classes?

Kapt不适用于Android Studio 3.0中的AutoValue

添加抽象的私有getter和公共setter的正确方法是什么?

Kotlin:如何从另一个类访问字段?

使用 Kotlin 创建自定义 Dagger 2 范围

应用程序在使用 Google Play 服务时遇到问题

将字符串编码为Kotlin中的UTF-8

如何在 firebase 数据库中使用 kotlin 协程