为什么Kotlin需要函数引用语法? [英] Why does Kotlin need function reference syntax?

查看:64
本文介绍了为什么Kotlin需要函数引用语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin文档说它支持高阶函数.为什么在传递顶级函数作为参数时,语言甚至需要::function语法?

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?

给出:

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

有关此处的函数引用语法的更多信息.

推荐答案

科特林语言设计旨在避免模棱两可的情况,即某些情况下某些内容同时正确和不正确.例如,如果您允许建议的语法:

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

::是有关意图的明确信号.因此,在isOdd情况下,您只会得到一个错误,因为您现在具有不重叠的可能性:

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

这就是为什么Kotlin避免导致歧义状态的事情.就像IDE和静态分析一样,您也可以像编译器一样迅速发现问题.如果您开始允许使用这种宽松的语法,您将开始遇到复合歧义,例如用作infix函数时等等.语言设计比哦,让我们键入更少的字符"要复杂得多,因为如果只看一个用例而忽略所有其他用例,那么复杂度矩阵比您想像的要大得多.

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需要函数引用语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆