Skip to content

Instantly share code, notes, and snippets.

@dacr
Created May 13, 2023 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/c1250395e2ca14b9018ef807609f87a0 to your computer and use it in GitHub Desktop.
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/9d1a18e7ed3cabb5a54dd1022412846cc86d6031
// 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 NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// 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.2.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