背景
最近Springをやる機会あり、Kotlinをやりました。
Javaよりかなり便利ですと実感しましたので、自分みたいな人にCheatSheetみたいなメモを共有できたらいいかと思います。
ログ
- Java
System.out.print("Hello World!");
System.out.println("Hello World!");
- Kotlin
print("Hello World!")
println("Hello World!")
変数と定数
- Java
String name = "これは変数";
final String name = "これは定数";
- Kotlin
var name = "これは変数"
val name = "これは定数"
空判定
- Java
// その他、isNullとかの関数も使える
if (text != null) {
int length = text.length();
}
- Kotlin
text?.let {
val length = text.length
}
// オプション型最高
val length = text?.length
String組合
- Java
String firstName = "名前";
String lastName = "苗字";
String message = "名前の構成: " + firstName + " " + lastName;
- Kotlin
val firstName = "名前"
val lastName = "苗字"
val message = "名前の構成: $firstName $lastName"
改行
- Java
String text = "1行目\n" +
"2行目\n" +
"3行目";
- Kotlin
// \nあんまに使わない
val text = """
|1行目
|2行目
|3行目
""".trimMargin()
演算子
- 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;
String text = x > 0 ? "正数" : "正数じゃない";
- 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
// 三項ないです
val text = if (x > 0)
"正数"
else "正数じゃない"
オブジェタイプ判定と変換
- Java
if (object instanceof Car) {
}
Car car = (Car) object;
- Kotlin
if (object is Car) {
}
var car = object as Car
case判定
- Java
int score = // 点数を入れる;
String grade;
switch (score) {
case 10:
case 9:
grade = "高い";
break;
case 8:
case 7:
case 6:
grade = "普通";
break;
case 5:
case 4:
grade = "まあまあ";
break;
case 3:
case 2:
case 1:
grade = "低い";
break;
default:
grade = "普通";
}
- Kotlin
var score = // 点数を入れる
var grade = when (score) {
9, 10 -> "高い"
in 6..8 -> "普通"
4, 5 -> "まあまあ"
in 1..3 -> "低い"
else -> "普通"
}
forルール
- Java
for (int i = 1; i <= 10 ; i++) { }
for (int i = 1; i < 10 ; i++) { }
for (int i = 10; i >= 0 ; i--) { }
for (int i = 1; i <= 10 ; i+=2) { }
for (int i = 10; i >= 0 ; i-=2) { }
for (String item : collection) { }
for (Map.Entry<String, String> entry: map.entrySet()) { }
- Kotlin
for (i in 1..10) { }
for (i in 1 until 10) { }
for (i in 10 downTo 0) { }
for (i in 1..10 step 2) { }
for (i in 10 downTo 0 step 2) { }
for (item in collection) { }
for ((key, value) in map) { }
Map
- Java
// Java9以降想定
final List<Integer> listOfNumber = List.of(1, 2, 3, 4);
final Map<Integer, String> keyValue = Map.of(1, "金メダル",
2, "銀メダル",
3, "銅メダル");
- Kotlin
// 似ています
val listOfNumber = listOf(1, 2, 3, 4)
val keyValue = mapOf(1 to "金メダル",
2 to "銀メダル",
3 to "銅メダル")
ForEach
- Java
cars.stream().filter(car -> car.speed > 100)
.forEach(car -> System.out.println(car.speed));
- Kotlin
// 似ています
cars.filter { it.speed > 100 }
.forEach { println(it.speed)}
関数
- Java
void doSomething() {
...
}
void doSomething(int... numbers) {
...
}
int getScore() {
...
return score;
}
- Kotlin
fun doSomething() {
...
}
fun doSomething(vararg numbers: Int) {
...
}
fun getScore(): Int {
...
return score
}
// 簡易化できる
fun getScore(): Int = score
コンストラクタ
- Java
public class Hoge {
private Hoge() {
...
}
public static int getTest(int score) {
...
return score;
}
}
- Kotlin
class Hoge private constructor() {
companion object {
fun getTest(score: Int): Int {
...
return score
}
}
}
// もしくはobjectで定義
object Hoge {
fun getTest(score: Int): Int {
...
return score
}
}
GetSet関数
- 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
// 開発者の定義1行で便利すぎる
data class Developer(val name: String, val age: Int)
クラスExtension
- Java
public class Utils {
...
public static int triple(int value) {
return 3 * value;
}
}
int result = Utils.triple(3);
// 拡張というより、関数を追加する感じ
- Kotlin
fun Int.triple(): Int {
return this * 3
}
var result = 3.triple()
// 拡張の対象は全部のクラス
Enum
- Java
public enum Direction {
NORTH(1),
SOUTH(2),
WEST(3),
EAST(4);
int direction;
Direction(int direction) {
this.direction = direction;
}
public int getDirection() {
return direction;
}
}
- Kotlin
enum class Direction(val direction: Int) {
NORTH(1),
SOUTH(2),
WEST(3),
EAST(4);
}