Reputation: 949
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
}
}
Upvotes: 18
Views: 108263
Reputation: 69
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
Upvotes: 2
Reputation: 100358
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.
Upvotes: 29