18

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

2 Answers 2

29

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, But I Also do something inside constructor
@hugerde what about using init {} block?
@AndriiAbramov Thank you, This is what I need, I will use init block with constructor.
2

I'll just add some info and give real example. When you want to initialize class && trigger some event, like some method, in Python we can simply call self.some_func() being in __init__ or even outside. In Kotlin we're restricted from calling simple in the context of the class, i.e.:

class SomeClass { this.cannotCallFunctionFromHere() } 

For such purposes I use init. It's different from constructor in a way that we don't clutter class schema && allows to make some processing.

Example where we call this.traverseNodes before any further actions are done with the methods, i.e. it's done during class initialization:

 class BSTIterator(root: TreeNode?) { private var nodes = mutableListOf<Int>() private var idx: Int = 0 init { this.traverseNodes(root) } fun next(): Int { val return_node = this.nodes[this.idx] this.idx += 1 return return_node } fun hasNext(): Boolean { when { this.idx < this.nodes.size -> { return true } else -> { return false } } } fun traverseNodes(node: TreeNode?) { if(node!!.left != null) { this.traverseNodes(node.left) } this.nodes.add(node.`val`) if(node!!.right != null) { this.traverseNodes(node.right) } } } 

Hope it also helps someone

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.