Kotlin 类型与泛型参数不匹配

Kotlin 类型与泛型参数不匹配,kotlin,Kotlin,我正在尝试运行以下代码,但遇到以下编译器错误:错误:(12,9)类型不匹配:推断的类型是Child,但应为Parent abstract class Parent<T> { abstract fun hi() } class Child: Parent<String>() { override fun hi() { println("Hi from child") } } fun main(args: Array<Strin

我正在尝试运行以下代码,但遇到以下编译器错误:
错误:(12,9)类型不匹配:推断的类型是Child,但应为Parent

abstract class Parent<T> {
    abstract fun hi()
}
class Child: Parent<String>() {
    override fun hi() {
        println("Hi from child")
    }
}

fun main(args: Array<String>) {
    println("Hello, world!")
    test(Child())
}

fun test(parent: Parent<Any>) {
    parent.hi()
}
抽象类父类{
抽象趣味(英文)
}
类子级:父级(){
超驰风喜(){
println(“Hi from child”)
}
}
趣味主线(args:Array){
println(“你好,世界!”)
测试(Child())
}
趣味测试(家长:家长){
parent.hi()
}
但是Java的等价物,如预期的那样工作:

public class HelloWorld {

    public static void main(String[] args) {
        test(new Child());
    }

    public static void test(Parent object) {
        object.hi();
    }
}

abstract class Parent<T> {
    public abstract void hi();
}

class Child extends Parent<String> {

    public void hi() {
        System.out.println("Hi from child");
    }
}
公共类HelloWorld{
公共静态void main(字符串[]args){
测试(新孩子());
}
公共静态无效测试(父对象){
object.hi();
}
}
抽象类父类{
公开摘要无效hi();
}
类子级扩展父级{
公共图书馆{
System.out.println(“Hi from child”);
}
}
Kotlin代码有什么问题?

您希望
Parent
成为
Parent
的子类型。因为
String
Any
的子类型,所以您要查找的是协方差。您可以使用
out
关键字将
Parent
的类型参数标记为这样:

abstract class Parent<out T> {
    abstract fun hi()
}
您希望
Parent
成为
Parent
的子类型。因为
String
Any
的子类型,所以您要查找的是协方差。您可以使用
out
关键字将
Parent
的类型参数标记为这样:

abstract class Parent<out T> {
    abstract fun hi()
}

Java代码似乎正在使用原始类型:
公共静态无效测试(父对象)
。这可能是一个因素。您的Java代码似乎正在使用原始类型:
公共静态无效测试(父对象)
。这可能是一个因素。