【问题标题】:How to use function in another class in kotlin?如何在 kotlin 的另一个类中使用函数?
【发布时间】:2021-01-14 21:06:48
【问题描述】:

我是 Kotlin 的新手。我有课程,我想在另一个课程中调用函数我尝试使用example 中的答案,但它给了我expecting member declaration error

如何使用它?

这是我的课

class MyClass() {
 //Do stafff
 val msg="Text"

 MyObject.sendMsg("msg") //getting here error
}


//Another file i have this object file
object MyObject{
  fun sendMsg(msg:String){
    println("I get your message $msg")
  }
}

【问题讨论】:

  • 函数调用只能在函数/构造函数中进行,或者作为对属性的赋值。您的 MyObject.sendMsg("msg") 电话只是在公开场合。

标签: java android kotlin


【解决方案1】:

你不能只在类体中执行代码。例如你可以声明一个方法

class MyClass() {
    //Do stafff
    val msg="Text"

    fun test() {
        MyObject.sendMsg("msg") //getting here error
    }
}

【讨论】:

  • 所以如果我想在测试中调用 MyClass 是否可以调用另一个类?
  • 是的,您可以从其他类方法或独立函数中调用您的类的方法
猜你喜欢
  • 1970-01-01
  • 2022-01-05
  • 2020-03-28
  • 2022-12-11
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
相关资源
最近更新 更多