Jus12
Jus12

Reputation: 18024

Is it possible to overload the '=' or '==' operators to mean something apart from assignment or equality?

I need to overload either the = or == to behave differently than assignment or equality. Suppose I have the code:

case class Col(name:String) 
def foo(col:Col, data:Any):SomeType = ??? // SomeType is another type 

val age = Col("age")
foo(age, 21)

I would like to provide syntactic sugar for foo(age, 21) as follows:

case class Col(name:String) {
   def ===(data:Any) = foo(this, data)
}

Then I can do:

age === 21 // works (returns SomeType)

What I would have liked to do:

age = 21 // does not work

or even

age == 21 // will not work as expected (== must return Boolean)

Is it possible? (prefer the = method)

Upvotes: 1

Views: 544

Answers (3)

Jus12
Jus12

Reputation: 18024

With ==, we can do it as described in Aleksey's answer (i.e., using separate methods for Int, String, etc instead of Any. The closest we can get to using = as something other than assignment is the following (based on another SO answer):

type SomeType = (String, Any)
case class Col(name:String) { 
  private var x: SomeType = _
  def value = x
  def value_=(data: Any):SomeType = ("hi", data)
}

val age = Col("age")

age.value = 21 // returns SomeType

Upvotes: 1

yǝsʞǝla
yǝsʞǝla

Reputation: 16412

You can do this:

scala> class A { def ==(o: Int) = "Donno" }
defined class A

scala> new A {} == 1
res2: String = Donno

scala> new A {} == "1"
<console>:12: warning: comparing values of types A and String using `==' will always yield false
       new A {} == "1"
                ^
res3: Boolean = false

scala> new A {} == new A {}
<console>:12: warning: comparing values of types A and A using `==' will always yield false
       new A {} == new A {}
                ^
res4: Boolean = false

or this:

scala> class A { def ==(o: Any, s: String) = s }
defined class A

but not this:

scala> class A { def ==(o: Any) = "Donno" }
<console>:10: error: type mismatch;
 found   : String("Donno")
 required: Boolean
       class A { def ==(o: Any) = "Donno" }
                                  ^

If you override a function you can't change it's return type. You can however overload it by changing it's signature.

p.s. please don't do it :)

Upvotes: 4

Incerteza
Incerteza

Reputation: 34884

Possible. Look into canEqual, hashCode and equals methods.

Upvotes: 1

Related Questions