将一个Java类转换为通用的Kotlin类会改变调用哪个函数。

huangapple 未分类评论42阅读模式
英文:

Casting a java class to a generic kotlin class alters which function is called

问题

我有以下的 Kotlin 类

    abstract class Base<I> {
        open fun test(value: I)  {
            Log.i("Base", value.toString());
        }
    }
    abstract class SubClass : Base<Long>() {
        abstract override fun test(value: Long);
    }

还有一个继承它们的 Java 类

    public class SubSubClass extends SubClass {
        @Override
        public void test(final long value) {
            Log.i("SubSubClass", value + "");
        }
    }

现在以下代码产生了奇怪的行为

    t.test(123)
    (t as Base<Long>).test(123)

期望输出

    I/SubSubClass: 123
    I/SubSubClass: 123

发生了什么如何修复?(注意我无法真正更改由 Room 生成的 Java 类
英文:

I have the following kotlin classes:

abstract class Base&lt;I&gt; {
    open fun test(value: I)  {
        Log.i(&quot;Base&quot;, value.toString());
    }
}
abstract class SubClass : Base&lt;Long&gt;() {
    abstract override fun test(value: Long);
}

And a java class that inherits from them:

public class SubSubClass extends SubClass {
    @Override
    public void test(final long value) {
        Log.i(&quot;SubSubClass&quot;, value + &quot;&quot;);
    }
}

Now the following code produces weird behavior

t.test(123)
(t as Base&lt;Long&gt;).test(123)

&gt;I/SubSubClass: 123    
&gt;I/Base: 123

while I would expect

&gt;I/SubSubClass: 123
&gt;I/SubSubClass: 123

What's going on here? And how can it be fixed? (Note: I can't really change the java class because it's generated by room)

huangapple
  • 本文由 发表于 2020年4月5日 03:43:37
  • 转载请务必保留本文链接:https://java.coder-hub.com/61033823.html
匿名

发表评论

匿名网友

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

确定