期待会员减免

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

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

在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变体,但更为详细。

请参阅有关构造函数的Kotlin参考 。