如何在Kotlin中进行擦除? [英] How does erasure work in Kotlin?

查看:125
本文介绍了如何在Kotlin中进行擦除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中,将编译以下代码:

In Kotlin, the following code compiles:

class Foo {
    fun bar(foo: List<String>): String {
        return ""
    }

    fun bar(foo: List<Int>): Int {
        return 2;
    }
}

但是,此代码没有:

class Foo {
    fun bar(foo: List<String>): String {
        return ""
    }

    fun bar(foo: List<Int>): String {
        return "2";
    }
}

编译此错误将导致以下错误:

Compiling this will cause the following error:

Error:(8, 5) Kotlin: Platform declaration clash: The following declarations have the same JVM signature (foo(Ljava/util/List;)Ljava/lang/String;):
    fun foo(layout: List<Int>): String
    fun foo(layout: List<String>): String

在Java中,两个示例都不会编译:

In Java, neither example will compile:

class Foo {
    String bar(List<Integer> foo) {
        return "";
    }

    Integer bar(List<String> foo) {
        return 2;
    }
}

class Foo {
    String bar(List<Integer> foo) {
        return "";
    }

    String bar(List<String> foo) {
        return "2";
    }
}

不出所料,这两个先前的代码片段都会生成熟悉的编译器错误:

Unsurprisingly, both of the prior snippets generate the familiar compiler error:

Error:(13, 12) java: name clash: bar(java.util.List<java.lang.String>) and bar(java.util.List<java.lang.Integer>) have the same erasure

令我惊讶的是,第一个Kotlin示例完全可以工作,而第二个(如果可行)为什么第二个Kotlin示例却失败了? Kotlin是否将方法的返回类型视为其签名的一部分?此外,与Java相比,为什么Kotlin中的方法签名尊重完整的参数类型?

What surprises me is that the first Kotlin example works at all, and second, if it works, why does the second Kotlin example fail? Does Kotlin consider a method's return type as part of its signature? Furthermore, why do method signatures in Kotlin respect the full parameter type, in contrast with Java?

推荐答案

实际上Kotlin知道示例中这两种方法之间的区别,但jvm不会.这就是为什么它是平台"冲突的原因.

Actually Kotlin knows the difference between the two methods in your example, but jvm will not. That's why it's a "platform" clash.

您可以使用@JvmName批注来编译第二个示例:

You can make your second example compile by using the @JvmName annotation:

class Foo {
  @JvmName("barString") fun bar(foo: List<String>): String {
    return ""
  }

  @JvmName("barInt") fun bar(foo: List<Int>): String {
    return "2";
  }
}

这个注释之所以存在是因为这个原因.您可以在 interop中阅读更多内容.文档.

This annotation exists for this very reason. You can read more in the interop documentation.

这篇关于如何在Kotlin中进行擦除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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