I have a scala (2.10.4) application where email addresses are passed around a lot, and I'd like to implement an abstraction that's called at IO to "sanitize" already validated email addresses.
Using scala.Proxy
is almost what I want, but I'm running into issues with asymmetric equality.
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
}
I'd like to have
val sanitizedEmail = SanitizedEmailAddress("[email protected]")
val expected = "[email protected]"
assert(sanitizedEmail == expected) // => true
assert(expected == sanitizedEmail) // => true, but this currently returns false :(
Or something with similar functionality. Is there any non-cumbersome way to do this?
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
Thanks for your help.
I don't think it's possible, sorry.
I'm not sure it's quite right to want that, either. If a String
is truly equal to a SanitizedEmailAddress
, then what does the SanitizedEmailAddress
wrapper actually denote?
I think it would be more consistent to have String
not comparable to a SanitizedEmailAddress
, and require users to "sanitize" input before comparing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With