【问题标题】:Pass a parameter to generic function with several upper bounds将参数传递给具有多个上限的泛型函数
【发布时间】:2018-08-06 18:01:30
【问题描述】:

无法将参数传递给Combiner().combine() 函数。

Android Studio 无法识别 arg 扩展 Foo 并实现 Bar。我做错了什么?

abstract class Foo {
    val f: Int = 1
}

interface Bar {
    val b: String get() = "a"
}

class Combiner {
    fun <T> combine(arg: T): Pair<Int, String> where T : Foo, T : Bar {
        return arg.f to arg.b
    }
}

class Program {
    fun main() {
        val list: List<Foo> = arrayListOf()
        list.forEach {
            if (it is Bar) {
                Combiner().combine(it) //inferred type Any is not a subtype of Foo
            }
        }
    }
}

这就是它与 Java 的工作方式:

public static class Program {
    public static void main() {
        List<Foo> list = new ArrayList<>();
        for (Foo item : list) {
            if (item instanceof Bar) {
                new Combiner().combine((Foo & Bar) item);
            }
        }
    }
}

为 Kotlin 创建错误报告:https://youtrack.jetbrains.com/issue/KT-25942

【问题讨论】:

标签: generics casting kotlin polymorphism


【解决方案1】:

如果这有任何帮助,显然如果你用 Java 编写同样的东西:

abstract class Foo {
    public int getF() {
        return 1;
    }
}

interface Bar {
    default String getB() {
        return "a";
    }
}

static class Combiner {
    public <T extends Foo & Bar> Pair<Integer, String> combine(T arg) {
        return Pair.create(arg.getF(), arg.getB()); 
    }
}

public static class Program {
    public static void main() {
        List<Foo> list = new ArrayList<>();
        list.forEach(foo -> {
            if(foo instanceof Bar) {
                new Combiner().combine(foo);
            }
        });
    }
}

然后由于以下消息它将无法工作:

原因:不存在类型变量的实例,因此 Foo 符合 Bar 推理变量 T 具有不兼容的界限: 下界:Foo 上限:Foo, Bar

现在如果您将cast 添加到Bar

        list.forEach(foo -> {
            if(foo instanceof Bar) {
                new Combiner().combine((Bar)foo);
            }
        });

问题很明显:(Bar)foo 现在是 Bar,而不是 Foo


因此,您需要知道一个确切的类型,它是 FooBar 的子类才能转换为它。

所以如果是这样的话,那么可以工作——事实上,在Java中,它实际上是编译的:

public static <T extends Foo & Bar> T toBar(Foo foo) {
    //noinspection unchecked
    return (T)foo;
}

public static class Program {
    public static void main() {
        List<Foo> list = new ArrayList<>();
        list.forEach(foo -> {
            if(foo instanceof Bar) {
                new Combiner().combine(toBar(foo));
            }

事实上,下面的测试成功

public static class Pair<S, T> {
    public Pair(S first, T second) {
        this.first = first;
        this.second = second;
    }

    S first;
    T second;

    public static <S, T> Pair<S, T> create(S first, T second) {
        return new Pair<>(first, second);
    }
}

public static <T extends Foo & Bar> T toBar(Foo foo) {
    //noinspection unchecked
    return (T)foo;
}

public class Blah extends Foo implements Bar {
}

@Test
public void castSucceeds() {
    Blah blah = new Blah();
    List<Foo> list = new ArrayList<>();
    list.add(blah);

    list.forEach(foo -> {
        if(foo instanceof Bar) {
            Pair<Integer, String> pair = new Combiner().combine(toBar(foo));
            assertThat(pair.first).isEqualTo(1);
            assertThat(pair.second).isEqualTo("a");
        }
    });
}

这意味着理论上应该在 Kotlin 中工作:

class Program {
    fun main() {
        val list: List<Foo> = arrayListOf()
        list.forEach {
            if (it is Bar) {
                @Suppress("UNCHECKED_CAST")
                fun <T> Foo.castToBar(): T where T: Foo, T: Bar = this as T

                Combiner().combine(it.castToBar()) // <-- magic?
            }
        }
    }
}

除非它不起作用,因为它说:

类型推断失败:信息不足,无法推断参数 T。请明确指定。

所以在 Kotlin 中,我所能做的就是:

class Blah: Foo(), Bar {
}

Combiner().combine(it.castToBar<Blah>())

这显然不能保证,只有当我们知道它的特定子类型是 Foo 和 Bar 的子类时。


所以我似乎无法找到一种方法让 Kotlin 将一个类转换为它自己的类型,因此“相信我”它可以安全地转换为一个 T,它本身也是 Foo 和酒吧。

但是通过 Java 让 Kotlin 相信它是可行的:

import kotlin.Pair;

public class ForceCombiner {
    private ForceCombiner() {
    }

    private static <T extends Foo & Bar> Pair<Integer, String> actuallyCombine(Bar bar) {
        T t = (T)bar;
        return new Combiner().combine(t);
    }

    public static Pair<Integer, String> combine(Bar bar) {
        return actuallyCombine(bar);
    }
}

class Program {
    fun main() {
        val list: List<Foo> = arrayListOf()
        list.forEach {
            if (it is Bar) {
                val pair = ForceCombiner.combine(it) // <-- should work

除了ForceCombiner 现在只有在我们在 Kotlin 界面上使用 @JvmDefault 时才有效

interface Bar {
    @JvmDefault
    val b: String get() = "a"
}

现在说:

// Inheritance from an interface with `@JvmDefault` members is only allowed with -Xjvm-default option
class Blah: Foo(), Bar { 
}

所以我实际上并没有尝试过-Xjvm-default 选项,但是it could work?见here how you can do that

  • 使用-Xjvm-default=enable,每个@JvmDefault 方法只生成接口中的默认方法。在这种模式下,使用 @JvmDefault 注释现有方法会破坏二进制兼容性,因为它会有效地从 DefaultImpls 类中删除该方法。
  • 使用-Xjvm-default=compatibility,除了默认接口方法外,还会在 DefaultImpls 类中生成一个兼容性访问器,它通过合成访问器调用默认接口方法。在这种模式下,使用 @JvmDefault 注释现有方法是二进制兼容的,但会产生更多字节码中的方法。

此外,@JvmDefault 需要 target 1.8,但 Android 的脱糖应该现在处理默认接口。

【讨论】:

    【解决方案2】:

    错误信息有些模糊。让我们帮助 Kotlin 编译器吧:

    fun main(vararg args: String) {
         val list: List<Foo> = arrayListOf()
         list.forEach {
              val bar = it as Bar
              val c = Combiner().combine(bar) // inferred type Bar is not a subtype of Foo
         }
    }
    

    智能演员正在做的就是 - 他们正在演员。将Foo 转换为Bar 后,无法保证它不再是Foo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多