I have several classes with fields that should be case insensitive, and I would like to put instances of these classes in HashMaps and look at them using a string case insensitive.
Instead of using toLowerCase every time I want to index an instance by its row or search for an instance by its row, I instead tried to encapsulate this logic in the CaseInsensitiveString class:
class CaseInsensitiveString ( val _value : String ) { override def hashCode = _value.toLowerCase.hashCode override def equals(that : Any) = that match { case other : CaseInsensitiveString => other._value.toLowerCase ==_value.toLowerCase case other : String => other.toLowerCase == _value.toLowerCase case _ => false } override def toString = _value } object CaseInsensitiveString { implicit def CaseInsensitiveString2String(l : CaseInsensitiveString) : String = if ( l ==null ) null else l._value implicit def StringToCaseInsensitiveString(s : String) : CaseInsensitiveString = new CaseInsensitiveString(s) def apply( value : String ) = new CaseInsensitiveString(value) def unapply( l : CaseInsensitiveString) = Some(l._value) }
Can anyone suggest a cleaner or better approach?
One drawback I came across is using junit assertEquals as follows:
assertEquals("someString", instance.aCaseInsensitiveString)
It fails, stating that it was expecting "someString", but received CaseInsensitiveString <"someString">.
If I reverse the order of the variables in assertEquals, then it works, perhaps because then it calls the equals function in the CaseInsensitiveString class. I'm currently working on this, keeping the order the same (so expected is actually expected), but call .toString on CaseInsensitiveString:
assertEquals("someString", instance.aCaseInsensitiveString.toString)
This also works:
assertEquals(CaseInsensitiveString("someString"), instance.aCaseInsensitiveString)
Is it possible to add an implicit value equal to String to solve this problem?
string scala
Alex black
source share