如何做到高级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()

相关推荐
晓晓hh8 小时前
JavaSE学习——迭代器
java·开发语言·学习
Laurence8 小时前
C++ 引入第三方库(一):直接引入源文件
开发语言·c++·第三方库·添加·添加库·添加包·源文件
kyriewen119 小时前
你点的“刷新”是假刷新?前端路由的瞒天过海术
开发语言·前端·javascript·ecmascript·html5
014-code9 小时前
String.intern() 到底干了什么
java·开发语言·面试
421!9 小时前
GPIO工作原理以及核心
开发语言·单片机·嵌入式硬件·学习
极梦网络无忧9 小时前
OpenClaw 基础使用说明(中文版)
python
codeJinger9 小时前
【Python】操作Excel文件
python·excel
摇滚侠9 小时前
JAVA 项目教程《苍穹外卖-12》,微信小程序项目,前后端分离,从开发到部署
java·开发语言·vue.js·node.js
@insist12310 小时前
网络工程师-生成树协议(STP/RSTP/MSTP)核心原理与应用
服务器·开发语言·网络工程师·软考·软件水平考试
野生技术架构师10 小时前
2026年牛客网最新Java面试题总结
java·开发语言