Kotlin メモ : takeIf
Java
public Hoge createFromParcel(Parcel source) {
final int length = source.readInt();
final byte[] data;
if (length > 0) {
data = new byte[length];
source.readByteArray(data);
} else {
data = null;
}
return new Hoge(data);
}
Kotlin 変換直後
override fun createFromParcel(source: Parcel): Hoge {
val length = source.readInt()
val data: ByteArray?
if (length > 0) {
data = ByteArray(length)
source.readByteArray(data)
} else {
data = null
}
return Hoge(data)
}
source.run {} を使う
override fun createFromParcel(source: Parcel): Hoge = source.run {
val length = readInt()
val data: ByteArray?
if (length > 0) {
data = ByteArray(length)
readByteArray(data)
} else {
data = null
}
Hoge(data)
}
also を使う
override fun createFromParcel(source: Parcel): Hoge = source.run {
val length = readInt()
val data: ByteArray?
if (length > 0) {
data = ByteArray(length).also { readByteArray(it) }
} else {
data = null
}
Hoge(data)
}
if 式にしてみる
override fun createFromParcel(source: Parcel): Hoge = source.run {
val length = readInt()
val data: ByteArray? = if (length > 0) {
ByteArray(length).also { readByteArray(it) }
} else {
null
}
Hoge(data)
}
length に let を使う
override fun createFromParcel(source: Parcel): Hoge = source.run {
val length = readInt()
val data: ByteArray? = if (length > 0) {
length.let { ByteArray(it).also { readByteArray(it) } }
} else {
null
}
Hoge(data)
}
readInt() に takeIf を使う
override fun createFromParcel(source: Parcel): Hoge = source.run {
val data: ByteArray? = readInt()
.takeIf { it > 0 }
?.let { ByteArray(it).also { readByteArray(it) } }
Hoge(data)
}
0 件のコメント:
コメントを投稿