Kotlin

Enum Class書き方

enum class Trend { INCREASING, DECREASING, PEAK }

sortedWith

data class CustomDate( val year: Int, val month: Int, val day: Int ) fun main() { var custumDates = listOf( CustomDate(2023, 1, 1), CustomDate(2023, 1, 2), CustomDate(2023, 2, 1), CustomDate(2022, 1, 1), CustomDate(2022, 1, 2), CustomDate(…

compareValuesByを使ってもっと簡単にComparableを実装する

data class CustomDate( val year: Int, val month: Int, val day: Int ) : Comparable<CustomDate> { override fun compareTo(other: CustomDate): Int { return compareValuesBy(this, other, CustomDate::year, CustomDate::month, CustomDate::day) } override fun t</customdate>…

Comparableを実装する

data class CustomDate( val year: Int, val month: Int, val day: Int ) : Comparable<CustomDate> { override fun compareTo(other: CustomDate): Int { if (year == other.year) { if (month == other.month) { return day - other.day } else { return month - other</customdate>…

getOrPut

val paths = mutableMapOf<Int, MutableSet<Int>>() ... paths[a]?.let { it.add(b) } ?: run { paths[a] = mutableSetOf(b) } もしgetOrPutを使うと、下記のようにすごく簡単になる val paths = mutableMapOf<Int, MutableSet<Int>>() ... paths.getOrPut(a) { mutableSetOf() }.add(b)</int,></int,>

ラベル付きループ

Kotlin: outer@for (i in 1..5) { for (j in 1..5) { println("i: $i, j: $j") if (j == 3) { continue@outer } } } Swift: outer: for i in 1...5 { for j in 1...5 { print("i: \(i), j: \(j)") if j == 3 { continue outer } } }

Kotlinのfor

1, 2, 3, 4, 5: for (i in 1..5) 1, 3, 5: for (i in 1..5 step 2) 1, 2, 3, 4: for (i in 1 until 5) 5, 4, 3, 2, 1: for (i in 5 downTo 1) 5, 3, 1: for (i in 5 downTo 1 step 2)

ArrayDeque

もしリストの先頭または末尾だけ操作する場合、ArrayDequeを使え!

Kotlin enumerated

val fruits = listOf("apple", "banana", "pear") fruits.forEachIndexed { index, fruit -> println(index) println(fruit) }

Priority Queue

Priority Queueはelementを追加時自動的にソートできる便利なコレクションである。一部のLeetCode問題ではPriority Queueを使わないとタイムアウトが発生する。(e.g. 問題502、問題1834、問題1962) これからPriority Queueの使い方を紹介します…

Kotlin Unwrap an Optional Variable

val name: String? = "Cecil" name?.let { println(it) } ?: run { println("name is null") }