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

相关推荐
寻星探路14 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
lly20240616 小时前
Bootstrap 警告框
开发语言
2601_9491465316 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧16 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX16 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb010316 小时前
C++课后习题训练记录Day98
开发语言·c++
ValhallaCoder16 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
猫头虎17 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
YUJIANYUE18 小时前
PHP纹路验证码
开发语言·php
仟濹18 小时前
【Java基础】多态 | 打卡day2
java·开发语言