我正在尝试将下面的代码从Java转换为Kotlin。
public class CreateShortcut extends Activity {
class WaitFor extends AsyncTask<Void,Void,Void> {
final int waitPeriod;
private WaitFor (int N) {
this.waitPeriod = N * 1000;
}
@Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(waitPeriod);
Intent bi = new Intent(shortcutId);
bi.putExtra("msg", "deny");
sendBroadcast(bi);
}
catch (InterruptedException ignore) {
}
return null;
}
}
...
这是转换后的 Kotlin 。
class CreateShortcut : AppCompatActivity() {
private class WaitFor (N: Int) : AsyncTask<Void, Void, Void>() {
val waitPeriod: Int = N * 1000
override fun doInBackground(vararg voids: Void): Void? {
try {
Thread.sleep(waitPeriod.toLong())
val bi = Intent(shortcutId)
bi.putExtra("msg", "deny")
sendBroadcast(bi)
} catch (ignore: InterruptedException) { /* Ignore */ }
return null
}
}
我的问题是,kotlin代码中的sendBroadcast是一个未解决的引用。
sendBroadcast是在上下文中定义的,如果我将该代码行修改为:
(this as CreateShortcut).sendBroadcast(bi)
Lint 警告“铸造永远不会成功”
但是代码工作正常。
我已经尝试了一个合格的this(即this @ CreateShortcut),而@CreateShortcut却无法解决。同样,this.sendBroadcast(intent)也无法解析。
我在网上找到的Kotlin广播接收器示例都只使用了不合格的“sendBroadcast”,但它们通常只是从 Activity 类中的函数进行调用,而不是从 Activity 中的内部类进行调用。
我被卡住了。有什么建议么??
谢谢
史蒂夫·S。
最佳答案
发生这种情况是因为默认情况下,在Kotlin中,嵌套类是静态的,而在Java中则不是。您必须将其限定为inner
才能重现Java代码的行为(非静态)。
在静态嵌套类中,您不能访问外部类的非静态成员。
private inner class WaitFor (N: Int) : AsyncTask<Void, Void, Void>()