Search code examples
scalaimplicit-conversion

scala implicit conversion for case object


I was referring to the answer posted in Scala implicit conversion for object

sealed trait Command {
  val typeName: String
  //This is required for implicit conversion.
  override def toString: String = typeName
}

object SendMessageCommand extends Command {
  override val typeName: String = "send_message"
}
object AddMessageCommand extends Command {
  override val typeName: String = "add_message1"
}
object UpdateMessageCommand extends Command {
  override val typeName: String = "update_message"
}
object DeleteMessageCommand extends Command {
  override val typeName: String = "delete_message"
}

//List of commands.
implicit val cmds: List[Command] = List(SendMessageCommand, AddMessageCommand, UpdateMessageCommand, DeleteMessageCommand)

//Convert given type T into type U.
implicit def convert[T, U](s: T)(implicit list: List[U]): Option[U] = {
  list.find(_.toString == s.toString)
}

implicit val convert3: Command => String =
  (v: Command) => v.typeName

val res1:String = UpdateMessageCommand
val res: Option[Command] = "add_message1"

I created my new convertor convert3 which converts Command => String . The above works , but I am not sure why the user has overidden string for the implicit conversion

  //This is required for implicit conversion.
  override def toString: String = typeName

Solution

  • This is answered in the post:

    Note: as I am comparing two type instance in conversion by converting them into string, I have to override toString method in Command for this use case.

    Because it's written for generic T and U (and they don't have bounds), the author can't call typeName.

    But honestly defining an implicit conversion like that (convert, not convert3) is a bad idea in the first place.