I'd like to use generics in companion object in this way:

class Foo<T> {
    /* ... */
    companion object {
        fun foo(args: List<T>) {
            /* ... */
        }
    }
}

Unfortunately the code above raise Unresolved reference: T error.

推荐答案

你要么像这样声明泛型

fun <T> foo(args: List<T>) { ... }

or, if you don't care about the type, you can use a star projection

fun foo(args: List<*>) { ... }

Kotlin相关问答推荐

Lambda和普通Kotlin函数有什么区别?

Compose:LaunchedEffect在密钥更改后不会重新启动

Kotlin中的增广赋值语句中的难以理解的错误

将文本与文本字段的内容对齐

在 Kotlin 中,为什么我们要在闭包中捕获值

扩展属性委托给实例属性

使用调度程序运行异步 Kotlin 代码

在 kotlin 中重载函数时,我在一些非常基本的代码上不断收到类型不匹配

compareBy 如何使用布尔表达式在 kotlin 中工作

将 Completable 转换为 Single 的规范方法?

Kotlin 有 array.indexOf 但我无法弄清楚如何做 array.indexOfBy { lambda }

将 Firebase 数据快照反序列化为 Kotlin 数据类

在 Koin 中提供一个 Instance 作为其接口

如何将命令行参数传递给Gradle Kotlin DSL

Kotlin解构when/if语句

API 26 上未显示 Android 通知

参数不匹配;SimpleXML

在Kotlin中使用@Service时引发异常

如何限制kotlin协程的最大并发性

Recyclerview: listen to padding click events