Expecting member declaration in Kotlin

2019-02-28 20:59发布

问题:

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

}}

回答1:

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.



标签: kotlin