【问题标题】:The closure as parameter behind the default parameter in KotlinKotlin 中默认参数后面的闭包作为参数
【发布时间】:2020-04-21 18:19:30
【问题描述】:

我有一个功能

fun <T> get(path: String, params: MutableMap<String, Any>? = null, headers: MutableMap<String, String>? = null, resolver: ResponseResolver<T>): HttpRequest<T>

哪个 ResponseResolver 是类型别名

typealias ResponseResolver<T> = (HttpResponse) -> T

当我像下面这样调用 get 方法时:

get("/somePath", mutableMapOf("key" to "value")){ httpResponse -> ......some code(Last line is a List<SomeClass>)

然后 Intellij 告诉我

Type inference failed: 

fun <T> get
(
path: String,
params: MutableMap<String, Any>? = ...,
headers: MutableMap<String, String>? = ...,
resolver: ResponseResolver<T> /* = (HttpResponse) → T */
)
: HttpRequest<T>

cannot be applied to
(
String,
MutableMap<String, Any>,
(HttpResponse) → List<SomeClass>
)

我不确定在应用闭包作为某些具有默认参数的函数的参数时是否有任何限制。

【问题讨论】:

  • 注意问号,fun 需要一个可空的MutableMap&lt;String, Any&gt;?,但得到一个不可空的MutableMap&lt;String, Any&gt;

标签: kotlin lambda parameters closures type-inference


【解决方案1】:

Kotlin 并不确切知道 mutableMapOf("key" to "value") 是什么。

明确是参数还是标题

get("/somePath", headers = mutableMapOf("key" to "value")){ httpResponse -&gt; ......some code(Last line is a List&lt;SomeClass&gt;)

get("/somePath", mutableMapOf&lt;String, Any&gt;("key" to "value")){ httpResponse -&gt; ......some code(Last line is a List&lt;SomeClass&gt;)

【讨论】:

  • 有趣的是,当我显式声明类型参数时,intellij 提示“删除显式类型参数”。现在我知道问题在于缺少类型参数。谢谢!
猜你喜欢
  • 2017-03-11
  • 2010-10-07
  • 2018-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 1970-01-01
相关资源
最近更新 更多