- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 240字
- 2021-06-25 20:49:24
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.
- Spring Cloud Alibaba核心技術與實戰案例
- LabVIEW Graphical Programming Cookbook
- 企業級Java EE架構設計精深實踐
- ASP.NET Core Essentials
- PyTorch自然語言處理入門與實戰
- Mastering LibGDX Game Development
- 深入淺出React和Redux
- Bootstrap 4 Cookbook
- Extreme C
- UI設計全書(全彩)
- Nagios Core Administration Cookbook(Second Edition)
- 微信小程序開發實戰:設計·運營·變現(圖解案例版)
- Visual C++程序設計與項目實踐
- 交互設計師成長手冊:從零開始學交互
- PostgreSQL Developer's Guide