I'm writing a DSL where I ultimately want to be able to have my own string type where I can do things like
var s:BString = "123"
if ("123" == s) ...
and also
var d:Double = s + 5.0
I have addition basically working with implicit conversions along with 5.0 + s
I also have == working one way by overriding the equals method in my 'BString' class ,where the first argument (left side) is a BString.
The problem is somehow overriding the Java String equals. I had a look at the String.equals() source code, and the equals method takes a Java Object which I can't seem to get working with implicit conversions. The equals method there then casts the object to a string, so I think unless I have a subclass of (final) String I'm SOL.
Is there any other approach? Ideas?
class BString(val string: String) {
override def toString() = string
def toDouble:Double = string.toDouble
def +(bs:BString) = string.toDouble + bs.toDouble
def +(d:Double) = string.toDouble + d
override def equals(x$1:Any):Boolean = string == x$1.toString
}
object Test {
implicit def string2BString(x:String) = new BString(x)
implicit def double2BString(x:Double) = new BString(x.toString)
implicit def bString2Object(x:BString) = { // never being reached
println("OO");
x.asInstanceOf[Object]
}
def main(args: Array[String]) {
var y:BString = "1.1"
println(y + 1.1) //2.2
println(1.2 + y) //2.3
println("1.1" == y) // false :-(
println("1.1" equals y) // false :-(
println("1.1" equals bString2Object(y)) // also false
println(y == "1.1") // true
}
}