[英]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. 它汇编。
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.