Expecting member declaration in Kotlin

Viewed 77807

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
    }
}
2 Answers

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

Related