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?

概要

ZIO Schemaは、スキーマ定義ライブラリです。
この記事では、ZIO SchemaのdefaultValueという機能について、サンプルコードを交えて解説します。

defaultValue とは?

defaultValue: Either[String, A] は、Schema[A] に対してデフォルト値を計算して返すメソッドです。

戻り値は Either 型で、

  • Right(a): デフォルト値 a (型 A) が正常に計算された場合
  • Left(error): デフォルト値の計算に失敗した場合、エラーメッセージが返されます

標準的な型のデフォルト値

ZIO Schema は、標準的な型(StringIntBooleanLocalDateTimeUUID など)に対して、デフォルト値を自動的に計算します。

  • String: 空文字列 ("")
  • Int: 0
  • Boolean: false
  • Option[A]: None
  • その他の型: その型のゼロ値 (例えば、List なら空リスト)

サンプルコード

DeriveSchema.genでスキーマを自動導出し、
schema.defaultValueでデフォルト値を生成しています。

import zio.{Console, ZIO, ZIOAppArgs, ZIOAppDefault}

import java.util.UUID

object Main extends ZIOAppDefault {
  import zio.schema._
  case class Person(id: UUID, name: String, age: Int, isStudent: Boolean = false)
  implicit val schema: Schema[Person] = DeriveSchema.gen[Person]

  val defaultPerson = schema.defaultValue.toOption

  override def run: ZIO[ZIOAppArgs, Any, Any] =
    Console.printLine(schema.defaultValue) // Right(Person(df02ab42-f649-4802-a2e6-1e7309568b1c,,0,false))
}

まとめ

ZIO Schema の defaultValue は、データの初期化や欠損値の補完など、様々な場面で役立つ便利な機能です。デフォルト値を適切に活用することで、より安全で信頼性の高いアプリケーションを開発できます。

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?