高级Kotlin强化实战(二)
-
-
-
-
- [2.13 constructor 构造器](#2.13 constructor 构造器)
- [2.14 Get Set 构造器](#2.14 Get Set 构造器)
- [2.15 操作符](#2.15 操作符)
- [2.16 换行](#2.16 换行)
-
-
-
2.13 constructor 构造器
java
//Java
public class Utils {
private Utils() {
}
public static int getScore(int value) {
return 2 * value;
}
}
kotlin
//Kotlin
class Utils private constructor() {
companion object {
fun getScore(value: Int): Int {
return 2 * value
}
}
}
// 或者
object Utils {
fun getScore(value: Int): Int {
return 2 * value
}
}
2.14 Get Set 构造器
java
//Java
public class Developer {
private String name;
private int age;
public Developer(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
kotlin
//kotlin
data class Developer(val name: String, val age: Int)
2.15 操作符
java
//Java
final int andResult = a & b;
final int orResult = a | b;
final int xorResult = a ^ b;
final int rightShift = a >> 2;
final int leftShift = a << 2;
final int unsignedRightShift = a >>> 2;
kotlin
//kotlin
val andResult = a and b
val orResult = a or b
val xorResult = a xor b
val rightShift = a shr 2
val leftShift = a shl 2
val unsignedRightShift = a ushr 2
2.16 换行
java
//Java
String text = "First Line\n" +
"Second Line\n" +
"Third Line";
kotlin
//kotlin
val text = """
|First Line
|Second Line
|Third Line
""".trimMargin()