Skip to content

Instantly share code, notes, and snippets.

@mingyang91
Last active July 19, 2022 14:34
Show Gist options
  • Save mingyang91/580b8e02fd9371ccdb8a1d55a0deea5f to your computer and use it in GitHub Desktop.
Save mingyang91/580b8e02fd9371ccdb8a1d55a0deea5f to your computer and use it in GitHub Desktop.
Sum two case class in scala3
@experimental
object Test extends App :
val a = CCA("a", 2, 3.0)
val b = CCB(4.5, 128.toByte)
val res = sum[CCA, CCB, CCC](a, b)
println(res)
@experimental
def sum[A <: Product, B <: Product, C <: Product](a: A, b: B)
(using ma: Mirror.ProductOf[A],
mb: Mirror.ProductOf[B],
mc: Mirror.ProductOf[C],
ev: Concat[ma.MirroredElemTypes, mb.MirroredElemTypes] =:= mc.MirroredElemTypes): C =
val concatted = Tuple.fromProductTyped(a) ++ Tuple.fromProductTyped(b)
mc.fromTuple(ev(concatted))
case class CCA(a: String, b: Int, c: Double)
case class CCB(d: Float, e: Byte)
case class CCC(a: String, b: Int, c: Double, d: Float, e: Byte)
@mingyang91
Copy link
Author

Result:

/Users/<...>/.sdkman/candidates/java/22.1.0.r17-grl/bin/java ...
CCC(a,2,3.0,4.5,-128)

Process finished with exit code 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment