官术网_书友最值得收藏!

Declaring functions

Everything is an object in Java. If you have a method that doesn't rely on any state, it still must be wrapped by a class. You're probably familiar with a lot of Util classes in Java that only have static methods, and their only purpose is to satisfy the language requirements and bundle those methods together.

In Kotlin, a function can be declared outside of a class instead of the following code:

public class MyFirstClass {

public static void main(String[] args) {
System.out.println("Hello world");
}
}

It's enough to have:

fun main(args: Array<String>) {
println("Hello, world!")
}

Functions declared outside of any class are already static. 

Many examples in this book assume that the code we provide is wrapped in the main function. If you don't see a signature of the function, it probably should be:
fun main(args: Array<String>).

The keyword to declare a function is fun. The argument type comes after the argument name, and not before. And if the function doesn't return anything, the return type can be omitted completely.

What if you do want to declare the return type? Again, it will come after the function declaration:

fun getGreeting(): String {
return "Hello, world!"
}

fun main(args: Array<String>) {
println(getGreeting())
}

There are lots of other topics regarding function declarations, such as default and named arguments, default parameters, and variable numbers of arguments. We'll introduce them in the following chapters, with relevant examples.

主站蜘蛛池模板: 新沂市| 安西县| 江山市| 禹城市| 文安县| 原平市| 夏邑县| 新乐市| 蚌埠市| 日土县| 上犹县| 将乐县| 都江堰市| 柳河县| 桦甸市| 绩溪县| 沂水县| 宜春市| 利川市| 井冈山市| 桦南县| 龙里县| 邻水| 安宁市| 宜黄县| 巨鹿县| 射洪县| 扶沟县| 鄂托克旗| 呼图壁县| 巴楚县| 沈丘县| 达拉特旗| 峨眉山市| 鹿泉市| 内黄县| 双辽市| 禹城市| 仪陇县| 达孜县| 宁蒗|