期待在Kotlin的成员声明

hug*_*rde 3 kotlin

我想在构造函数中分配我的类变量,但是我得到一个期望成员声明的错误

 class YLAService {


var context:Context?=null

class YLAService constructor(context: Context) {
    this.context=context;// do something

}}
Run Code Online (Sandbox Code Playgroud)

nha*_*man 15

在Kotlin中,您可以使用如下构造函数:

class YLAService constructor(val context: Context) {

}
Run Code Online (Sandbox Code Playgroud)

更短:

class YLAService(val context: Context) {

}
Run Code Online (Sandbox Code Playgroud)

如果你想先做一些处理:

class YLAService(context: Context) {

  val locationService: LocationManager

  init {
    locationService = context.getService(LocationManager::class.java)
  }
}
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用辅助构造函数:

class YLAService {

  val context: Context

  constructor(context: Context) {
    this.context = context
  }

}
Run Code Online (Sandbox Code Playgroud)

这看起来更像Java变体,但更冗长.

请参阅关于构造函数Kotlin参考.

  • @hugerde 使用 `init {}` 块怎么样? (2认同)