Few days ago I started to learn Cats and I want to implement method appendOptional
for Map[String, _: Show]
.
I started with the following idea:
def appendOptional[T: Show](to: Map[String, String], values: (String, Option[T])*): Map[String, String] =
values.foldLeft(values) {
case (collector, (key, Some(value))) =>
collector + (key -> implicitly[Show[T]].show(value))
case (collector, _) => collector
}
And to use it like:
def createProps(initial: Map[String, String], name: Option[String], age: Option[Int])
val initial = Map("one" -> "one", "two" -> "two")
val props = appendOptional(initial, "name" -> name, "age" -> age)
I understand that this approach is quite naive and straightforward because implicitly[Show[T]].show(value)
will actually lookup for Show[Any]
.
Also, I had an idea to accept HList
with context bound, but I have not found any example of that.
One more variant is to create a lot of overloaded methods (as it is done in a lot of libraris):
def appendOptional[T1: Show, T2: Show](to: Map[String, String], v1: (String, Option[T1], v2: (String, Option[T2])))
Question: Is there a way to define context bound for varargs functions?