我有一个scala(2.10.4)应用程序,其中电子邮件地址传递很多,我想实现一个在IO调用的抽象来"清理"已经验证的电子邮件地址.
使用scala.Proxy几乎是我想要的,但我遇到了不对称平等的问题.
class SanitizedEmailAddress(s: String) extends Proxy with Ordered[SanitizedEmailAddress] {
val self: String = s.toLowerCase.trim
def compare(that: SanitizedEmailAddress) = self compareTo that.self
}
object SanitizedEmailAddress {
def apply(s: String) = new SanitizedEmailAddress(s)
implicit def sanitize(s: String): SanitizedEmailAddress = new SanitizedEmailAddress(s)
implicit def underlying(e: SanitizedEmailAddress): String = e.self
}
Run Code Online (Sandbox Code Playgroud)
我想要
val sanitizedEmail = SanitizedEmailAddress("Blah@Blah.com")
val expected = "blah@blah.com"
assert(sanitizedEmail == expected) // => true
assert(expected == sanitizedEmail) // => true, but this currently returns false :(
Run Code Online (Sandbox Code Playgroud)
或者具有类似功能的东西.有没有非繁琐的方法吗?
assert(sanitizedEmail.self == expected) // => true (but pretty bad, and someone will forget)
// can have a custom equality method and use the "pimp-my-lib" pattern on strings, but then we have to remember to use that method every time
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
我认为这是不可能的,抱歉。
我也不确定这样的愿望是否正确。如果 aString确实等于 a SanitizedEmailAddress,那么包装器实际上表示什么SanitizedEmailAddress?
String我认为不与 a 比较会更加一致SanitizedEmailAddress,并要求用户在比较之前“清理”输入。