简体   繁体   English

Kotlin-具有通用返回类型的抽象函数

[英]Kotlin - abstract function with generic return type

I am new to Kotlin and really worried whether I am writing proper syntax or not. 我是Kotlin的新手,真的很担心我是否在编写正确的语法。 I have a super class and I want to write a generic abstract function as below. 我有一个超类,我想编写如下的通用抽象函数。

abstract class A {
    abstract fun <T> getText() : Test<T>
}

class B : A() {
    override fun <T> getText(): Test<T> {
        return Test1() // Error - Required Test<T>, found Test1
    }
}

class C : A() {
    override fun <T> getText(): Test<T> {
        return Test2() // Error - Required Test<T>, found Test2
    }
}

class Test1 : Test<String>() {

}

class Test2 : Test<Int>() {

}

Can I solve this kind of problem with some sort of proper syntax. 我可以用某种适当的语法解决此类问题吗? I guess I am doing some mistake? 我想我做错了吗? Can anybody please help? 有人可以帮忙吗?

What you're doing cannot be correct, because it would allow the following code: 您正在执行的操作是不正确的,因为它将允许以下代码:

val test: Test<Int> = B().getText()

B().getText() tries to return Test1() , which is Test<String> . B().getText()尝试返回Test1() ,即Test<String> But because the return type can be anything, its valid. 但是因为返回类型可以是任何东西,所以它是有效的。 This breaks the type system. 这破坏了类型系统。

This is the answer you're looking for: 这是您要寻找的答案:

abstract class A<T> {
    abstract fun getText() : Test<T>
}

class B : A<String>() {
    override fun getText(): Test<String> = Test1()
}

class C : A<Int>() {
    override fun getText(): Test<Int> = Test2()
}

class Test1 : Test<String>()
class Test2 : Test<Int>()
open class Test<T>

You just need to move parameter T from the method signature to the class. 您只需要将参数T从方法签名移至类。

Bonus: I updated the above snippet to more idiomatic Kotlin 奖励:我将以上代码片段更新为更惯用的Kotlin

You likely want to enforce the type from the class rather than the method, due to Kiskae's example. 由于Kiskae的示例,您可能想从类而不是方法中强制执行类型。

For example: 例如:

abstract class A<T> {
    abstract fun getText() : Test<T>
}

can be extended using 可以使用扩展

class B : A<String>() ...

which will match the type for Test1 它将与Test1的类型匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM