【发布时间】:2019-02-20 17:57:04
【问题描述】:
我指的是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"
我创建了我的新转换器convert3,它可以转换 Command => String 。
上面的工作,但我不确定为什么用户为隐式转换覆盖了字符串
//This is required for implicit conversion.
override def toString: String = typeName
【问题讨论】: