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

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.

主站蜘蛛池模板: 海盐县| 博兴县| 双江| 德昌县| 伊金霍洛旗| 东山县| 遵化市| 南木林县| 海兴县| 辽阳市| 望都县| 乌拉特中旗| 丹东市| 玛多县| 武汉市| 稷山县| 雷山县| 海阳市| 福海县| 定陶县| 巩留县| 定陶县| 肥城市| 会理县| 昌图县| 宁德市| 武汉市| 正安县| 大港区| 肇东市| 郓城县| 昆山市| 东辽县| 邯郸市| 河北省| 名山县| 上杭县| 花莲县| 松原市| 蒙山县| 特克斯县|