Extension functions for generic classes in Kotlin

后端 未结 3 1404
南笙
南笙 2020-12-15 21:15

What\'s wrong with my extension function below

class Foo {
    fun  Foo.plus(that: Foo): Foo = throw Exception()         


        
3条回答
  •  隐瞒了意图╮
    2020-12-15 21:24

    Your method plus expects the parameter to have the same generic type parameter T as the receiver. Hence, you can't add a Foo to a Foo.

    If you want to be able to add all types of Foo, than you need to declare your extension function like so:

    operator fun  Foo.plus(that: Foo): Foo = throw Exception()
    

提交回复
热议问题