故障保险withFallback():为什么kotlin编译器无法推断lambda类型? [英] Failsafe withFallback(): why kotlin compiler fails to infer lambda type?
问题描述
我的kotlin代码中包含以下内容:
I have following in my kotlin code:
return Failsafe.with<Boolean>(retryPolicy)
// Here I want fall back to false
.withFallback { -> false} // Does not work
.get { ->
publish(event)
true
}
Kotlin编译器抱怨:
Kotlin compiler complains that:
错误:(89,14)Kotlin:重载分辨率不明确:
Error:(89, 14) Kotlin: Overload resolution ambiguity:
withFallback(p0:(()-> Boolean!)!)的公共最终乐趣:) SyncFailsafe!在net.jodah.failsafe.SyncFailsafe中定义
public final fun withFallback(p0: (() -> Boolean!)!): SyncFailsafe! defined in net.jodah.failsafe.SyncFailsafe
withFallback(p0:(()-> Unit)!)的公共最终乐趣:SyncFailsafe!在net.jodah.failsafe.SyncFailsafe中定义
public final fun withFallback(p0: (() -> Unit)!): SyncFailsafe! defined in net.jodah.failsafe.SyncFailsafe
但是这种方式有效:
val fallback: () -> Boolean = { false }
return Failsafe.with<Boolean>(retryPolicy)
// Here I want fall back to false
.withFallback(fallback) // Works
.get { ->
publish(event)
true
}
有人可以解释一下为什么它不能在括号内使用lambda文字吗?以及如何使其与lambda内联一起工作?
Could somebody explain me why it does not work with lambda literal outside brackets? And how to make it work with lambda inline?
推荐答案
如果您写
val fallback: () -> Unit = { -> false }
您还将看到它也可以编译(它只是丢弃结果).所以 {->false}
可以用于两种类型的()->布尔值
和()->单位
,编译器不知道您要哪个.
you'll see it compiles as well (it just discards the result). So { -> false}
can be used for both types () -> Boolean
and () -> Unit
and the compiler doesn't know which you want.
要使用lambda,请在此处指定所需的类型:
So to use a lambda, specify the desired type there:
.withFallback({ -> false} as () -> Boolean)
或创建没有过载的扩展功能,例如:
or create an extension function without an overload, e.g.:
fun <T, F> FailsafeConfig<T, F>.withFallbackT(fallback: () -> T) = withFallback(fallback)
return Failsafe.with<Boolean>(retryPolicy)
.withFallbackT { -> false}...
这篇关于故障保险withFallback():为什么kotlin编译器无法推断lambda类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!