scala ADTs via sealed traits - is there a way to deserialize from string in a generic fashion
假设我具有以下特征
和以下代数数据类型
1 2 3 4 5 6 7 8 9 10 11 12 13 |
现在,可以使用以下方法将字符串实例反序列化到Animal ADT中。
1 2 3 4 5 6 7 |
@oxbow_lakes在回答的结尾提到:
Can't instantiate easily from persisted value. This is also true but,
except in the case of huge enumerations (for example, all currencies),
this doesn't present a huge overhead.
我发现以下事实:当您添加新值时,需要将其显式添加到反序列化代码中,因为它容易出错(我认为编译器会向我警告穷举匹配,但请看一下上面的
有没有更好的办法? (如果不使用标准的scala工具集,是第三方的吗?)
此问题已由
https://github.com/lloydmeta/enumeratum
您的代码可以这样写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import enumeratum._ import enumeratum.EnumEntry.Lowercase sealed trait Animal extends EnumEntry with Lowercase object Animal extends Enum[Animal] { val values = findValues case object Dog extends Animal case object Cat extends Animal case object Owl extends Animal } val dogName = Animal.Dog.entryName val dog = Animal.withNameInsensitive(dogName) |
您可以尝试做的一件事是使用反射获取扩展
有关获取