Created
March 30, 2018 02:17
-
-
Save tototoshi/dc90c616f1728e293deaa9cc4fdd05ae to your computer and use it in GitHub Desktop.
shapless example (Show)
This file contains 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 com.example | |
import shapeless._ | |
import shapeless.labelled.FieldType | |
trait Show[A] { | |
def show(a: A): String | |
} | |
object Show { | |
def apply[A](f: A => String): Show[A] = new Show[A] { | |
override def show(a: A): String = f(a) | |
} | |
implicit def string: Show[String] = Show[String](identity) | |
implicit def int: Show[Int] = Show[Int](_.toString) | |
implicit def list[T](implicit tShow: Show[T]): Show[List[T]] = | |
Show[List[T]] { | |
_.map(tShow.show).mkString("[", ", ", "]") | |
} | |
implicit def hnil: Show[HNil] = Show[HNil] { _ => | |
"" | |
} | |
implicit def hlist[K <: Symbol, H, T <: HList]( | |
implicit | |
witness: Witness.Aux[K], | |
hShow: Lazy[Show[H]], | |
tShow: Show[T]): Show[FieldType[K, H] :: T] = | |
Show[FieldType[K, H] :: T] { | |
case h :: HNil => | |
witness.value.name + "=" + hShow.value.show(h) | |
case h :: t => | |
witness.value.name + "=" + hShow.value.show(h) + ", " + tShow.show(t) | |
} | |
implicit def generic[T, U](implicit gen: LabelledGeneric.Aux[T, U], | |
ev: LowPriority, | |
f: Lazy[Show[U]]): Show[T] = Show[T] { a => | |
val cls = a.getClass.getName | |
val hash = System.identityHashCode(a) | |
val fields = f.value.show(gen.to(a)) | |
s"$cls@$hash($fields)" | |
} | |
} | |
object ShowSyntax { | |
implicit class showSyntax[A](a: A)(implicit s: Show[A]) { | |
def show: String = s.show(a) | |
} | |
} | |
case class Person(firstName: String, lastName: String, friends: List[Person]) | |
object Main { | |
import ShowSyntax._ | |
def main(args: Array[String]): Unit = { | |
val person = Person("John", | |
"Lennon", | |
List(Person("Paul", "McCartney", Nil), | |
Person("George", "Harrison", Nil), | |
Person("Ringo", "Starr", Nil))) | |
println(person.show) | |
// com.example.Person@400176287(firstName=John, lastName=Lennon, friends=[com.example.Person@1621417118(firstName=Paul, lastName=McCartney, friends=[]), com.example.Person@1245422131(firstName=George, lastName=Harrison, friends=[]), com.example.Person@762439731(firstName=Ringo, lastName=Starr, friends=[])]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment