【问题标题】:Expecting member declaration in Kotlin期待 Kotlin 中的成员声明
【发布时间】:2017-06-05 12:15:16
【问题描述】:

我想在构造函数中分配我的类变量,但我得到一个错误'期望成员声明'

class YLAService {

    var context:Context?=null

    class YLAService constructor(context: Context) {
        this.context=context;// do something
    }
}

【问题讨论】:

标签: kotlin


【解决方案1】:

在 Kotlin 中,您可以像这样使用构造函数:

class YLAService constructor(val context: Context) {

}

更短:

class YLAService(val context: Context) {

}

如果你想先做一些处理:

class YLAService(context: Context) {

  val locationService: LocationManager

  init {
    locationService = context.getService(LocationManager::class.java)
  }
}

如果你真的想使用辅助构造函数:

class YLAService {

  val context: Context

  constructor(context: Context) {
    this.context = context
  }

}

这看起来更像 Java 变体,但更冗长。

请参阅Kotlin reference on constructors

【讨论】:

  • 谢谢,但我也在构造函数中做了一些事情
  • @hugerde 使用init {} 块怎么样?
  • @AndriiAbramov 谢谢,这是我需要的,我将使用带有构造函数的 init 块。
【解决方案2】:

我将添加一些信息并给出真实示例。当你想初始化类&&触发一些事件,比如一些方法,在Python中我们可以简单地调用self.some_func()__init__甚至外面。在 Kotlin 中,我们被限制在类的上下文中调用 simple,即:

class SomeClass {
    this.cannotCallFunctionFromHere()
}

为此,我使用init。它与构造函数的不同之处在于我们不会弄乱类模式 && 允许进行一些处理。

在对方法执行任何进一步操作之前调用this.traverseNodes 的示例,即在类初始化期间完成:


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)
        }
    }

}

希望它也对某人有所帮助

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2012-06-22
    相关资源
    最近更新 更多