Superclass of companion seem unable to use generic parameter of class


Say I have this code layout.

class CompanionSuperclass<T>

class MainGenericClass<T>{
    companion object : CompanionSuperclass<T>

The last occurrence of T in that snippet is marked by IDEA as an unresolved reference, whereas it stand to reason that it shouldn’t be.


Why? There is no reason to assume that type parameter in class MainGenericClass is the same as in the compoanion object, especially considering objects cannot have parameter types.

I suspect what you want to achieve is this:

abstract class CompanionSuperclass<T>

class MainGenericClass<T>{
    companion object<T> : CompanionSuperclass<T>()

but it makes no sense as there is only one instance of the companion object for all instances of MainGenericClass and its subclasses - therefore the companion object must have a concrete type.

If you want to have a generic parameter in companion object’s functions you can get it like this:

abstract class CompanionSuperclass {
    fun <T> p(input: T) = print(input)

open class MainGenericClass<T>{
    companion object : CompanionSuperclass()

class SubClass : MainGenericClass<String>() {
    init {

although in this simple example you can omit <String> in invocation of function p as it can be inferred form the argument.