具有相同名称的并行可空和非空方法 [英] Parallel nullable and non-null method with same name

查看:62
本文介绍了具有相同名称的并行可空和非空方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提供两种名称相同的方法,它们可以接受可选或非可选输入:

I would like to offer two methods with the same name which can accept optional or non-optional input:

class Formatter {
    fun format(input: Number?) : String? {return number?.toString()}
    fun format(input: Number) : String {return number.toString()}
}

显然,由于JVM的限制,这是不可能的:

Apparently this is not possible due to JVM limitations:

平台声明冲突:以下声明具有相同的JVM签名(test(Lorg.example.Number;)Ljava/lang/String;):

Platform declaration clash: The following declarations have the same JVM signature (test(Lorg.example.Number;)Ljava/lang/String;):

是否存在可读的解决方法来实现相同的目标?我当前的解决方案是重命名一种方法(例如formatNonNull(input:Number)).

Is there a readable workaround to achieve the same goal? My current solution is to rename one method (e.g. formatNonNull(input: Number)).

奖金:我的Formatter类实际上是用Java编写的,看起来像这样:

Bonus: My Formatter-class is actually written in Java and looks like this:

class Formatter {
    @Nullable String format(@Nullable Number input) : String {return number != null ? number.toString(): null;}
}

应通过非null变体进行扩展:

It shall be extended by the non-null variant:

@NonNull String formatNonNull(@NonNull Number input) : String {return number.toString();}

是否有一种方法可以改善这一点,即不引入新名称(例如,使用kotlin扩展名)?

Is there a way to improve this i.e. without introducing a new name (e.g. with kotlin extension)?

推荐答案

有一个巧妙的技巧可以在JVM上解决此问题:

There's a neat hack to fix this on the JVM:

class Formatter {
    fun format(input: Number?) : String? {return number?.toString()}
    @JvmName("-formatNonNull") fun format(input: Number) : String {return number.toString()}
}

之所以起作用,是因为-是JVM字节码中的有效标识符字符,而不是Java语言中的字符.这意味着代码将被编译,您将能够在Kotlin中调用这两个方法,但是您将无法从Java调用名称中具有-的方法.这也消除了名称冲突,因为这些方法在字节码中将具有不同的名称.

The reason this works is that - is a valid identifier character in the JVM bytecode, but not in the Java language. This means that the code will compile and you'll be able to call both methods in Kotlin, but you won't be able to call a method that has - in its name from Java. This also eliminates the name clash since the methods will have different names in bytecode.

这篇关于具有相同名称的并行可空和非空方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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