一个不属于类的函数如何从类的函数中调用?

huangapple go评论63阅读模式
英文:

How does function that isn't part of a class can be called from a class's function?

问题

以下是翻译好的内容:

我对 Kotlin 还不太熟悉(有一些 Java 经验)。在 Java 中,每个函数(方法)都属于类(静态函数或实例函数)。在 Java 中,不可能在类外部编写函数。在 Kotlin 中,我看到这是可能的。我无法理解如何从类函数中调用一个不属于类范围的函数。有人可以解释一下吗?

代码示例:

class Wolf() {
    var image = "wolf.jpg"
    var food = "meat"
    val habitat = "forests"

    fun makeNoise() {
        println("Hooooow!")
        addNumbers(5, 6)
    }
}

fun addNumbers(a: Int, b: Int): Int {
    return a + b
}
英文:

I'm new in Kotlin (have some experience with Java). In java, each function (method) belong to class (static function or instance function). In Java It isn't possible to write a function outside a class .In kotlin i see that it is possible. I can't understand how, calling a function (that isn't part of a class scope) from a class function works.
Can someone explain me.
Code Example:
Class Wolf:

  class Wolf()
{
    var image = "wolf.jpg"
    var food = "meat"
    val habitat = "forests"

    fun makeNoise() {
        println("Hooooow!")
        addNumbers(5, 6)

    }
}

Method that isn't part of class:

   fun addNumbers (a:Int, b:Int): Int
 {
     return a+b
 }

答案1

得分: 1

kotlin 文档

> 在 Kotlin 中,函数可以在文件的顶层声明,这意味着你不需要创建一个类来保存一个函数,而在诸如 Java、C# 或 Scala 等语言中是必须要做的。除了顶层函数外,Kotlin 函数还可以被声明为局部函数、成员函数和扩展函数。

如果你想知道这是如何在 JVM 字节码中实现的,可以使用 IntelliJ 中的 "工具 -> Kotlin -> 显示 Kotlin 字节码",然后使用 "反编译" 功能。

你会看到,如果你将 addNumbers 放在一个名为 Wolf.kt 的文件中,那么 Kotlin 编译器将生成等效于以下 Java 字节码的代码:

public final class WolfKt {
   public static final int addNumbers(int a, int b) {
      return a + b;
   }
}

你可以使用 @file:JvmName("WolfFunctions") 来控制类的名称

英文:

From the kotlin docs:

> In Kotlin functions can be declared at top level in a file, meaning you do not need to create a class to hold a function, which you are required to do in languages such as Java, C# or Scala. In addition to top level functions, Kotlin functions can also be declared local, as member functions and extension functions.

If you are wanting to know how this is implemented in JVM bytecode you can use the "Tools -> Kotlin -> Show Kotlin Bytecode" then "Decompile" feature in IntelliJ.

You will see that if you put addNumbers in a Wolf.kt file, then the kotlin compiler generates the bytecode equivalent of:

public final class WolfKt {
   public static final int addNumbers(int a, int b) {
      return a + b;
   }
}

You can control the name of the class with @file:JvmName("WolfFunctions")

huangapple
  • 本文由 发表于 2020年10月12日 19:52:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64317349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定