Kotlin符号化パターン
5596 ワード
Kotlin Idioms
ここではKotlinでランダムでよく使われるパターンの集合です.大好きなパターンがあれば、pullリクエストを送信することで貢献できます.
DTOの作成(POJO/POCO)
data class Customer(val name: String, val email: String)
Customer
クラスには、次の機能があります.
data class Customer(val name: String, val email: String)
getter
(およびvars
の場合のsetter
)equals()
hashCode()
toString()
copy()
component1()
, component2()
,...,すべての属性(データクラス参照)関数パラメータのデフォルト値
fun foo(a: Int = 0, b: String = "") { ... }
リストをフィルタ
val positives = list.filter { x -> x > 0 }
あるいは、さらに短い:
val positives = list.filter { it > 0 }
文字列補間
println("Name $name")
インスタンスチェック
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
ペアのマッピング/リストを巡回
for ((k, v) in map) {
println("$k -> $v")
}
k
v
は何でもいいです.使用範囲
for (i in 1..100) { ... } // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
読み取り専用リスト
val list = listOf("a", "b", "c")
読み取り専用マッピング
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
アクセスマップ
println(map["key"])
map["key"] = value
怠惰な属性
val p: String by lazy {
// compute the string
}
拡張関数
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
単一インスタンスの作成(singleton)
object Resource {
val name = "Name"
}
空でない略語(If not null shorthand)の場合
val files = File("Test").listFiles()
println(files?.size)
空でない場合の略語(If not null and else shorthand)
val files = File("Test").listFiles()
println(files?.size ?: "empty")
空の場合、実行文(Executing a statement if null)
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
空でない場合は、文を実行します(Execute if not null)
val data = ...
data?.let {
... // execute this block if not null
}
空でない場合は、マップ空の値(Map nullable value if not null)
val data = ...
val mapped = data?.let { transformData(it) } ?: defaultValueIfDataIsNull
when文を使用して戻る(Return on when statement)
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
'try/catch'式
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// Working with result
}
'if'式
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
ビルダースタイルでUnitを返す方法(Builder-style usage of methods that return Unit)を使用する
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
単一式関数(Single-expression functions)
fun theAnswer() = 42
これは
fun theAnswer(): Int {
return 42
}
これは他のパターンと有効に結合でき、コードが短くなります.例:
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
オブジェクトインスタンスで複数のメソッドを呼び出す('with')
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
val myTurtle = Turtle()
with (myTurtle) { //draw a 100 pix square
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
Java 7の「try with resources」
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
汎用型情報を必要とする汎用関数の便利な形式(Convenient form for a generic function that requires the generic type information)
// public final class Gson {
// ...
// public T fromJson(JsonElement json, Class classOfT) throws JsonSyntaxException {
// ...
inline fun Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)
Nullブール値の使用(Consuming a nullable Boolean)
val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` is false or null
}