小编cer*_*hif的帖子

具有枚举约束的 Kotlin 泛型函数

我想做如下的事情:

inline fun<T: Enum<T>> myFunction(enumStr: String){
    T.valueOf(enumStr)
    //...
}
Run Code Online (Sandbox Code Playgroud)

这样我的泛型参数就被限制为枚举类类型,以便我可以访问 valueOf 函数。我收到一条错误消息,指出:
Type parameter 'T' cannot have or inherit a companion object, so it cannot be on the left hand side of dot

我理解这意味着我不能在泛型上使用伴随对象函数。有什么方法可以实现我想要的 - 将字符串转换为通用枚举?

generics enums kotlin companion-object

1
推荐指数
1
解决办法
2903
查看次数

Kotlin 在构造函数中初始化函数内部变量

在 Kotlin 中,未声明为 nullable 或 Lateinit 的变量必须在构造函数(或 init)中初始化。我正在尝试这样做:

class Foo{
    var foo:myType
    init{
        complicatedFooInit()
    }

    fun complicatedFooInit(){
         foo = //a whole bunch of code here
    }

}
Run Code Online (Sandbox Code Playgroud)

我仍然收到Property must be initialized or declared abstract错误。您可以通过在函数中创建myTypeanInt并将其设置为等于 3 来轻松重现此情况complicatedFooInit。显然有一些方法可以解决这个问题(只是不让它成为一个函数,让complicatedFooInitreturnmyType并将 foo 设置为等于它,等等)。我的问题是,为什么上面的代码无效?或者经过一些调整后它是否有效?

class init kotlin

0
推荐指数
1
解决办法
2326
查看次数

标签 统计

kotlin ×2

class ×1

companion-object ×1

enums ×1

generics ×1

init ×1