简体   繁体   English

函数可以是默认参数值吗?

[英]Can functions be default parameter values?

Kotlin docs states that "functions are first-class". Kotlin博士说“功能是一流的”。 I'm trying to use a function as a default value of a function extension. 我正在尝试使用函数作为函数扩展的默认值。 However the compiler isn't having any of it: 但是编译器没有任何一个:

fun <T> identity(x: T): T = x
fun <T, P> Channel<T>.dedupe(by: (T) -> P = ::identity): ReceiveChannel<T>
{
    ...
}

The error is Function invocation 'identity(...)' expected which kinda indicates Kotlin isn't really understanding what I want to do at all. 错误是Function invocation 'identity(...)' expected ,这有点表明Kotlin并不真正理解我想做什么。

Is there a way? 有办法吗?

I don't know why you get this error message, but the problem is type mismatch: the default value must make sense for any type parameters (subject to bounds). 我不知道为什么会收到此错误消息,但问题是类型不匹配:默认值必须对任何类型参数都有意义(受限于)。 Ie you need a (T) -> P , but ::identity can give you (T) -> T or (P) -> P . 即你需要一个(T) -> P ,但是::identity可以给你(T) -> T(P) -> P

Proof: if you change to 证明:如果你换到

fun <T, P> identity(x: T): P = throw Exception()
fun <T, P> List<T>.dedupe(by: (T) -> P = ::identity): Unit {}

it compiles. 它汇编。

Answer (which came out in comments below): 答案(见下面的评论):

If P is changed to Any? 如果P改为Any? , we should be able to use ::identity because (T) -> T is a subtype of (T) -> Any? ,我们应该能够使用::identity因为(T) -> T(T) -> Any?的子类型(T) -> Any? . Unfortunately, it doesn't work, but using a lambda instead of a function reference does: 不幸的是,它不起作用,但使用lambda而不是函数引用会:

fun <T> identity(x: T): T = x
fun <T> Channel<T>.dedupe(by: (T) -> Any? = { it }): ReceiveChannel<T>
{
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Kotlin 中,抽象函数的默认参数值是否被继承? - In Kotlin, are default parameter values to abstract functions inherited? 如何在Kotlin中使用默认构造函数参数值实例化对象? - How can I instantiate an object using default constructor parameter values in Kotlin? 使用反射调用具有默认参数值的函数 - Call a function with default parameter values using reflection Kotlin 具有多个默认 arguments 的函数:如何忽略值? - Kotlin functions with multiple default arguments: How to leave values out? 当一个参数是类时,使用默认值初始化类 - Initialize a class with default values when one parameter is a class 我可以在Kotlin中使用默认参数调用一个函数并强制其不存在吗? - Can I call a function in Kotlin with a default parameter and force it to be absent? 为什么可以在子类型的重写成员函数中省略默认值? - Why is it possible to omit default values in overridden member functions of sub-types? Kotlin 默认参数排序 - Kotlin default parameter ordering 注入参数的默认值 - Default value for injection parameter Kotlin:“ fun main(参数:数组)中的默认参数如何 <String> )”在不分配任何值的情况下打印“ guest” - Kotlin : How the default parameter in “ fun main(parameters: Array<String>) ” prints “guest” without assigning any values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM