I want to assign my class variable in constructor, but I get an error 'expecting member declaration'
class YLAService {
var context:Context?=null
class YLAService constructor(context: Context) {
this.context=context;// do something
}
}
In Kotlin you can use constructors like so:
class YLAService constructor(val context: Context) {
}
Even shorter:
class YLAService(val context: Context) {
}
If you want to do some processing first:
class YLAService(context: Context) {
val locationService: LocationManager
init {
locationService = context.getService(LocationManager::class.java)
}
}
If you really want to use a secondary constructor:
class YLAService {
val context: Context
constructor(context: Context) {
this.context = context
}
}
This looks more like the Java variant, but is more verbose.
See the Kotlin reference on constructors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With