Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expecting member declaration in Kotlin

Tags:

kotlin

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
    }
}
like image 623
hugerde Avatar asked Jun 05 '17 12:06

hugerde


Video Answer


1 Answers

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.

like image 147
nhaarman Avatar answered Sep 20 '22 23:09

nhaarman