如何在kotlin中分配同名的Class变量?

hug*_*rde 1 android kotlin

我想在构造函数中指定我的上下文,但是当我使用"this"时,ide警告我.我如何编写如下Java代码的代码,但是在Kotlin中:

这是java代码

public class LoginApiService {
    Context context;

    public LoginApiService(Context context) {
        this.context = context;
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我想要做的

class YLAService {


var context:Context?=null

class YLAService constructor(context: Context) {
    this.context=context
}
Run Code Online (Sandbox Code Playgroud)

}

Tod*_*odd 7

在Kotlin中,如果您在构造函数中提供var或者val在构造函数中,它将自动变为可以使用的属性.无需其他任务.

class LoginApiService(val context: Context) {

   // Example...
   fun doSomething() {
      context.doSomethingOnContext()
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 无缘无故地使用constructor关键字不是惯用的,@ todd提供的是典型的代码. (4认同)