Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Kotlin中需要成员声明_Kotlin - Fatal编程技术网

在Kotlin中需要成员声明

在Kotlin中需要成员声明,kotlin,Kotlin,我想在构造函数中分配我的类变量,但我得到一个错误“期望成员声明” class服务{ 变量上下文:上下文?=null 类服务构造函数(上下文:上下文){ this.context=context;//做点什么 } } 在Kotlin中,您可以使用如下构造函数: class YLAService constructor(val context: Context) { } 甚至更短: class YLAService(val context: Context) { } 如果要先进行一些处理,请

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

class服务{
变量上下文:上下文?=null
类服务构造函数(上下文:上下文){
this.context=context;//做点什么
}
}

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

class YLAService constructor(val context: Context) {

}
甚至更短:

class YLAService(val context: Context) {

}
如果要先进行一些处理,请执行以下操作:

class YLAService(context: Context) {

  val locationService: LocationManager

  init {
    locationService = context.getService(LocationManager::class.java)
  }
}
如果确实要使用辅助构造函数,请执行以下操作:

class YLAService {

  val context: Context

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

}
这看起来更像Java变体,但更详细


请看。

谢谢,但我也在里面做了一些事情constructor@hugerde使用
init{}
block怎么样?@AndriiAbramov谢谢,这就是我需要的,我将使用init block和构造函数。