Last active
February 3, 2026 20:22
-
-
Save dacr/c1250395e2ca14b9018ef807609f87a0 to your computer and use it in GitHub Desktop.
ZIO learning - playing with opaque types and zio-json / published by https://github.com/dacr/code-examples-manager #46741a15-42bc-42bf-b4c4-e067bd6ff680/42f4566cfe78d86192d7824f3f59eb23f809d600
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // summary : ZIO learning - playing with opaque types and zio-json | |
| // keywords : scala, zio, learning, json, pure-functional, opaque, opaque-types, @testable | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : 46741a15-42bc-42bf-b4c4-e067bd6ff680 | |
| // created-on : 2023-05-13T14:17:51+02:00 | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // run-with : scala-cli $file | |
| // --------------------- | |
| //> using scala "3.4.2" | |
| //> using dep "dev.zio::zio:2.0.13" | |
| //> using dep "fr.janalyse::zio-worksheet:2.0.13.0" | |
| //> using dep "dev.zio::zio-json:0.5.0" | |
| //> using options "-Yretain-trees" // When case classes are using default values | |
| // --------------------- | |
| import zio.*, zio.json.*, zio.worksheet.* | |
| import java.time.OffsetDateTime | |
| opaque type UserName = String | |
| object UserName { | |
| def apply(value: String): UserName = value | |
| given JsonCodec[UserName] = JsonCodec.string | |
| } | |
| opaque type LastSeenDateTime = OffsetDateTime | |
| object LastSeenDateTime { | |
| def apply(value: OffsetDateTime): LastSeenDateTime = value | |
| given JsonCodec[LastSeenDateTime] = JsonCodec.offsetDateTime | |
| } | |
| case class User( | |
| userName: UserName, | |
| lastSeen: LastSeenDateTime | |
| ) derives JsonCodec | |
| val json = | |
| """{ | |
| | "userName":"joe", | |
| | "lastSeen":"2021-04-09T17:19:17.000Z" | |
| |}""".stripMargin | |
| val app = | |
| for | |
| person <- ZIO.fromEither(json.fromJson[User]) | |
| _ <- Console.printLine(person.toJsonPretty) | |
| yield () | |
| app.unsafeRun |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment