Expecting member declaration in Kotlin

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Expecting member declaration in 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






kotlinlang.org/docs/reference/classes.html#constructors
– Miha_x64
Jun 5 '17 at 12:33




1 Answer
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.





Thank you, But I Also do something inside constructor
– hugerde
Jun 5 '17 at 12:17






@hugerde what about using init block?
– Andrii Abramov
Jun 5 '17 at 12:19


init





@AndriiAbramov Thank you, This is what I need, I will use init block with constructor.
– hugerde
Jun 5 '17 at 12:26






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard