0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

kotlinx.datetime.Instant を Parcelable にする

Last updated at Posted at 2021-09-12

はじめに

java.time.Instant は Serializable ではありませんが、kotlinx.datetime パッケージにある kotlinx.datetime.Instant は Serializable です。逆に、java.time.Instant は Parcelable であるのに対して kotlinx.datetime.Instant は Parcelable ではありません。

これを表にすると次のようになります。

Serializable Parcelizable
java.time.Instant
kotlinx.datetime.Instant

今回は、kotlinx.datetime.Instant を Parcelable にするコードを紹介します。

【追記】
こちらjava.time.Instant を Serializable にする方法を書きました。

実装

次のコードは、Nullable な Parcelable Instant を作るために必要なオブジェクトです。

object NullableInstantParceler : Parceler<Instant?> {
  override fun create(parcel: Parcel): Instant? {
    val str = parcel.readString() ?: return null
    return Instant.parse(str)
  }
  override fun Instant?.write(parcel: Parcel, flags: Int) {
    if (this == null) {
      parcel.writeValue(null)
    } else {
      parcel.writeString(this.toString())
    }
  }
}

そして、Nullable でない Parcelable Instant を作るために必要なオブジェクトは次のようになります。

object InstantParceler : Parceler<Instant> {
  override fun create(parcel: Parcel): Instant {
    val str = parcel.readString()
    require(str != null)
    return Instant.parse(str)
  }
  override fun Instant.write(parcel: Parcel, flags: Int) {
    parcel.writeString(this.toString())
  }
}

使用例

次のように使用します。

@Parcelize
data class MyData(
  val instant1: @WriteWith<InstantParceler> Instant,
  val instant2: @WriteWith<NullableInstantParceler> Instant?,
) : Parcelable
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?