从Java到Kotlin——方法

无参数、无返回值

1
2
3
fun hello() {
println("Hello, World!")
}

Java

1
2
3
public void hello() {
System.out.print("Hello, World!");
}

带参数、无返回值

1
2
3
fun hello(name: String) {
println("Hello, $name!")
}

Java

1
2
3
public void hello(String name){
System.out.print("Hello, " + name + "!");
}

参数带有默认值

1
2
3
fun hello(name: String = "World") {
println("Hello, $name!")
}

Java

1
2
3
4
5
6
7
public void hello(String name) {
if (name == null) {
name = "World";
}
System.out.print("Hello, " + name + "!");
}

带返回值

1
2
3
fun hasItems() : Boolean {
return true
}

Java

1
2
3
public boolean hasItems() {
return true;
}

简写

1
fun cube(x: Double) : Double = x * x * x

Java

1
2
3
public double cube(double x) {
return x * x * x;
}

传入数组

1
fun sum(vararg x: Int) { }

Java

1
public int sum(int... numbers) { }

主函数/Main方法

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

Java

1
2
3
public class MyClass {
public static void main(String[] args){ }
}

多个参数

1
2
3
4
5
fun main(args: Array<String>) {
openFile("file.txt", readOnly = true)
}
fun openFile(filename: String, readOnly: Boolean) : File { }

Java

1
2
3
4
5
public static void main(String[]args){
openFile("file.txt", true);
}
public static File openFile(String filename, boolean readOnly) { }

可选参数

1
2
3
4
5
6
7
8
9
10
11
12
13
fun main(args: Array<String>) {
createFile("file.txt")
createFile("file.txt", true)
createFile("file.txt", appendDate = true)
createFile("file.txt", true, false)
createFile("file.txt", appendDate = true, executable = true)
createFile("file.txt", executable = true)
}
fun createFile(filename: String, appendDate: Boolean = false, executable: Boolean = false): File { }

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static void main(String[]args){
createFile("file.txt");
createFile("file.txt", true);
createFile("file.txt", true, false);
createExecutableFile("file.txt");
}
public static File createFile(String filename) { }
public static File createFile(String filename, boolean appendDate) { }
public static File createFile(String filename, boolean appendDate, boolean executable) { }
public static File createExecutableFile(String filename) { }

泛型

1
2
3
4
5
6
fun init() {
val module = createList<String>("net")
val moduleInferred = createList("net")
}
fun <T> createList(item: T): List<T> { }

Java

1
2
3
4
5
public void init() {
List<String> moduleInferred = createList("net");
}
public <T> List<T> createList(T item) { }
坚持原创技术分享,您的支持将鼓励我继续创作!