とりあえず、JavaからKotlinへの一歩

# 背景
最近Springをやる機会あり、Kotlinをやりました。
Javaよりかなり便利ですと実感しましたので、自分みたいな人にCheatSheetみたいなメモを共有できたらいいかと思います。

# ログ
- Java
```java
System.out.print("Hello World!");
System.out.println("Hello World!");
```
- Kotlin
```kotlin
print("Hello World!")
println("Hello World!")
```
# 変数と定数
- Java
```java
String name = "これは変数";
final String name = "これは定数";
```
- Kotlin
```kotlin
var name = "これは変数"
val name = "これは定数"
```
# 空判定
- Java
```java
// その他、isNullとかの関数も使える
if (text != null) {
    int length = text.length();
}
```
- Kotlin
```kotlin
text?.let {
    val length = text.length
}
// オプション型最高
val length = text?.length
```
# String組合
- Java
```java
String firstName = "名前";
String lastName = "苗字";
String message = "名前の構成: " + firstName + " " + lastName;
```
- Kotlin
```kotlin
val firstName = "名前"
val lastName = "苗字"
val message = "名前の構成: $firstName $lastName"
```
# 改行
- Java
```java
String text = "１行目\n" +
              "２行目\n" +
              "３行目";
```
- Kotlin
```kotlin
// \nあんまに使わない
val text = """
        |１行目
        |２行目
        |３行目
        """.trimMargin()
```
# 演算子
- 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;
String text = x > 0 ? "正数" : "正数じゃない";
```
- 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
// 三項ないです
val text = if (x > 0)
              "正数"
           else "正数じゃない"
```
# オブジェタイプ判定と変換
- Java
```java
if (object instanceof Car) {
}
Car car = (Car) object;
```
- Kotlin
```kotlin
if (object is Car) {
}
var car = object as Car
```
# case判定
- Java
```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
```kotlin
var score = // 点数を入れる
var grade = when (score) {
    9, 10 -> "高い"
    in 6..8 -> "普通"
    4, 5 -> "まあまあ"
    in 1..3 -> "低い"
    else -> "普通"
}
```
# forルール
- Java
```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
```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
```java
// Java9以降想定
final List<Integer> listOfNumber = List.of(1, 2, 3, 4);

final Map<Integer, String> keyValue = Map.of(1, "金メダル",
                                             2, "銀メダル",
                                             3, "銅メダル");
```
- Kotlin
```kotlin
// 似ています
val listOfNumber = listOf(1, 2, 3, 4)
val keyValue = mapOf(1 to "金メダル",
                     2 to "銀メダル",
                     3 to "銅メダル")
```
# ForEach
- Java
```java
cars.stream().filter(car -> car.speed > 100)
　　　　　　　　.forEach(car -> System.out.println(car.speed));
```
- Kotlin
```kotlin
// 似ています
cars.filter { it.speed > 100 }
      .forEach { println(it.speed)}
```
# 関数
- Java
```java
void doSomething() {
   ...
}

void doSomething(int... numbers) {
   ...
}

int getScore() {
   ...
   return score;
}
```
- Kotlin
```kotlin
fun doSomething() {
   ...
}

fun doSomething(vararg numbers: Int) {
   ...
}

fun getScore(): Int {
   ...
   return score
}
// 簡易化できる
fun getScore(): Int = score
```
# コンストラクタ
- Java
```java
public class Hoge {

    private Hoge() { 
      ... 
    }
    
    public static int getTest(int score) {
        ...
        return score;
    }
}
```
- Kotlin
```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
```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)
```

# クラスExtension
- Java
```java
public class Utils {

    ...
    
    public static int triple(int value) {
        return 3 * value;
    }
    
}

int result = Utils.triple(3);
// 拡張というより、関数を追加する感じ
```
- Kotlin
```kotlin
fun Int.triple(): Int {
  return this * 3
}

var result = 3.triple()
// 拡張の対象は全部のクラス
```

# Enum
- Java
```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
```kotlin
enum class Direction(val direction: Int) {
    NORTH(1),
    SOUTH(2),
    WEST(3),
    EAST(4);
}
```