0

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
coder25
  • 2,363
  • 12
  • 57
  • 104

1 Answers1

1

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • The convertor ```implicit val convert3: Command => String = (v: Command) => v.typeName``` doesnot have any bounds, it still doesnot work without overriding toString – coder25 Feb 20 '19 at 10:16
  • Yes, it does. You just need a context which triggers it, e.g. `val x: String = SendMessageCommand` and you'll see. It'll work (and without the converter it won't) whether or not you override `toString`. – Alexey Romanov Feb 20 '19 at 10:43
  • But note it's more usual to write as `implicit def convert3(v: Command): String = v.typeName`. – Alexey Romanov Feb 20 '19 at 10:45
  • Wait, you already have this context. Just remove the `toString` override and the last line from the code in your question and see it still compiles: https://scalafiddle.io/sf/8ItX5lt/0. And if you remove `convert3`, the last line will be an error. – Alexey Romanov Feb 20 '19 at 11:41