case 对象的 Scala 隐式转换

scala implicit conversion for case 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"

我创建了我的新转换器 convert3 来转换 Command => String 。 以上有效,但我不确定为什么用户为隐式转换覆盖了字符串

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

这在 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.

因为它是为泛型 TU 编写的(并且它们没有边界),作者不能调用 typeName.

但老实说,像这样定义隐式转换(convert,而不是 convert3)首先是个坏主意。