Created
October 15, 2025 07:25
-
-
Save xuwei-k/e689e9be278b9fe397d3515895fe2326 to your computer and use it in GitHub Desktop.
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
| scalaVersion := "2.13.17" | |
| libraryDependencies += "com.chuusai" %% "shapeless" % "2.3.13" |
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
| package example | |
| import shapeless.:: | |
| import shapeless.HList | |
| import shapeless.HNil | |
| import shapeless.Generic | |
| class MyTypeClass[T](value: T) { | |
| def map[S](f: T => S): MyTypeClass[S] = | |
| new MyTypeClass[S](f(value)) | |
| def flatMap[S](f: T => MyTypeClass[S]): MyTypeClass[S] = | |
| f(value) | |
| } | |
| object MyTypeClass { | |
| implicit def nil: MyTypeClass[HNil] = | |
| new MyTypeClass[HNil](HNil) | |
| implicit def cons[H, T <: HList](implicit H: => MyTypeClass[H], T: => MyTypeClass[T]): MyTypeClass[H :: T] = | |
| for { | |
| h <- H | |
| t <- T | |
| } yield h :: t | |
| implicit def gen[P, A <: HList](implicit | |
| m: Generic.Aux[P, A], | |
| w: MyTypeClass[A] | |
| ): MyTypeClass[P] = | |
| w.map(a => m.from(a)) | |
| implicit def int: MyTypeClass[Int] = new MyTypeClass(3) | |
| } | |
| case class A( | |
| x: Int, | |
| y: C | |
| ) | |
| sealed trait C | |
| object C { | |
| case object C1 extends C | |
| } | |
| object Main { | |
| def main(args: Array[String]): Unit = { | |
| println(implicitly[MyTypeClass[A]]) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment