如何做到高级Kotlin强化实战?(三)

高级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()

相关推荐
千寻girling20 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook1 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风1 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风1 天前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
alexhilton1 天前
端侧RAG实战指南
android·kotlin·android jetpack
helloweilei2 天前
python 抽象基类
python
用户8356290780512 天前
Python 实现 PPT 转 HTML
后端·python
zone77392 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77392 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
Kapaseker2 天前
2026年,我们还该不该学编程?
android·kotlin