在Kotlin中,默认参数后面的闭包作为参数。

huangapple go评论68阅读模式
英文:

The closure as parameter behind the default parameter in Kotlin

问题

我有一个函数

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最后一行是List<SomeClass>) }

然后Intellij告诉我:

类型推断失败

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

不能应用于
(
String,
MutableMap<String, Any>,
(HttpResponse) -> List<SomeClass>
)

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

英文:

I have a function

fun &lt;T&gt; get(path: String, params: MutableMap&lt;String, Any&gt;? = null, headers: MutableMap&lt;String, String&gt;? = null, resolver: ResponseResolver&lt;T&gt;): HttpRequest&lt;T&gt;

which ResponseResolver is a type alias

typealias ResponseResolver&lt;T&gt; = (HttpResponse) -&gt; T

When i invoke the get method like below:

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

Then the Intellij tells me that

Type inference failed: 

fun &lt;T&gt; get
(
path: String,
params: MutableMap&lt;String, Any&gt;? = ...,
headers: MutableMap&lt;String, String&gt;? = ...,
resolver: ResponseResolver&lt;T&gt; /* = (HttpResponse) → T */
)
: HttpRequest&lt;T&gt;

cannot be applied to
(
String,
MutableMap&lt;String, Any&gt;,
(HttpResponse) → List&lt;SomeClass&gt;
)

在Kotlin中,默认参数后面的闭包作为参数。

I'm not sure if there is any strictions in applying the closure as the argument of some functions with default parameters.

答案1

得分: 1

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

请澄清它是参数还是标头。

get("/somePath", headers = mutableMapOf("key" to "value")){ httpResponse -> ......some code(最后一行是List<SomeClass>)

还是

get("/somePath", mutableMapOf<String, Any>("key" to "value")){ httpResponse -> ......some code(最后一行是List<SomeClass>)

英文:

Kotlin don't know exactly what mutableMapOf(&quot;key&quot; to &quot;value&quot;) is.

Clarify whether it's params or headers

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

or

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

huangapple
  • 本文由 发表于 2020年1月3日 14:43:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定