Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Generic work if generic is Int in Kotlin?

Tags:

I tried to make abstract class for testing because I found weird problem for using generics

abstract class Test<T> {
    open fun hello(vararg data: T) {
        print("Default function")
    }
}

This very simple abstract class has one opened method with vararg keyword. Problem can be reproduced by making another class which extends Test class.

class Hello : Test<Int>() {
    //Problem 1
    override fun hello(vararg data: Int) {
        super.hello(*data) //Problem 2
        println("Override function")
    }
}

About first problem, Kotlin says method doesn't override anything even though this method surely overrides something. Weirdly, this error happens randomly, so I can't tell exact way to reproduce this bug

Kotlin can't recognize codes

This error got removed when I add some codes (like really simple code such as println(), etc), but when you compile, it causes same error again.

About second problem, super.hello(*data) causes problem because this requires Array<out Int>, but found parameter is IntArray. I think Kotlin is considering IntArray and Array<*> as different class, but it shouldn't act like this...

enter image description here

I'm using Kotlin 1.4.10 which seems the latest version according to this site.

I'm posting this to check if these 2 problems are bug or if I did something incorrectly because when I change generic to String, all problems get removed. Are there any mistakes I made in these sample codes above?

like image 958
Mandarin Smell Avatar asked Nov 14 '20 12:11

Mandarin Smell


1 Answers

Known issue: https://youtrack.jetbrains.com/issue/KT-9495

As a workaround, you can use the boxed java.lang.Integer.

class Hello : Test<Integer>() {
    override fun hello(vararg data: Integer) {
        super.hello(*data)
        println("Override function")
    }
}
like image 65
ephemient Avatar answered Oct 01 '22 20:10

ephemient