在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和构造函数。