我指的是在scala中发布的对象隐式转换的答案
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
1条答案
按热度按时间tv6aics11#
这在帖子中得到了回答:
注意:当我通过将两个类型示例转换为字符串来比较转换中的两个类型示例时,我必须在这个用例的命令中重写tostring方法。
因为它是为普通人写的
T
以及U
(而且他们没有界限),作者不能打电话typeName
.但是诚实地定义一个这样的隐式转换(
convert
,不是convert3
)一开始是个坏主意。