Kotlin类型擦除-为什么只编译通用类型不同的函数却不能编译仅返回类型不同的函数? [英] Kotlin type erasure - why are functions differing only in generic type compilable while those only differing in return type are not?

查看:96

这些函数编译或不编译的原因与Kotlin的重载解析规则有关. Kotlin不使用预期的类型来解决重载,因此,当您调用此函数时:

 val x = bar(listOf(""))

... Kotlin编译器无法确定类型,并且不允许您通过明确指定x的类型来消除调用的歧义.

在第二种情况下,由于函数具有不同的参数类型,因此不存在重载解析问题,并且由于函数具有不同的返回类型(因此具有不同的擦除签名),因此也没有JVM名称冲突问题.因此,代码会编译.

While working on the answer of How does erasure work in Kotlin? I found out some things I did not yet understand, nor did I find any sources why it is that way.

Why is the following not compilable?

fun bar(foo: List<*>) = ""
fun bar(foo: List<*>) = 2

while the following is?

fun bar(foo: List<String>) = ""
fun bar(foo: List<Int>) = 2

For me it even gets more curious, when adding a generic type that isn't even used, i.e. the following compiles too:

fun bar(foo: List<*>) = ""
fun <T> bar(foo: List<*>) = 2 // T isn't even used

As the last one doesn't even use T and as we know, generics are erased at runtime, why does this one work, while the variant without generic type does not?

Within the byte code methods only differing in return type are allowed (already described in the above linked answer).

Any hints, sources and/or references are welcome.

Added this question now also at discuss.kotlinlang.org.

解决方案

The reason why these functions compile or don't compile is related to Kotlin's overload resolution rules. Kotlin does not use the expected type for resolving overloads, so when you call this function:

 val x = bar(listOf(""))

...there is no way for the Kotlin compiler to determine the type, and it does not allow you to disambiguate the call by specifying the type of x explicitly.

In the second case, there is no overload resolution problem because the functions have distinct parameter types, and there is no JVM name conflict problem because the functions have different return types (and thus different erased signatures). Therefore, the code compiles.

这篇关于Kotlin类型擦除-为什么只编译通用类型不同的函数却不能编译仅返回类型不同的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆