我想做如下的事情:
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
我理解这意味着我不能在泛型上使用伴随对象函数。有什么方法可以实现我想要的 - 将字符串转换为通用枚举?
在 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 设置为等于它,等等)。我的问题是,为什么上面的代码无效?或者经过一些调整后它是否有效?