首页 > 解决方案 > 如何在 kotlin 的另一个类中使用函数?

问题描述

我是 Kotlin 的新手。我有课,我想在另一个课上调用函数我尝试使用答案,它给了我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")
  }
}

标签: javaandroidkotlin

解决方案


您不能仅在类主体中执行代码。例如,您可以声明一个方法

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

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


推荐阅读