是否可能超载' ='或者' =='运营商除了转让或平等之外还意味着什么?

时间:2016-01-15 07:00:11

标签: scala

我需要重载===,使其行为与赋值或相等不同。假设我有代码:

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

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

我想为foo(age, 21)提供语法糖,如下所示:

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

然后我可以做:

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

我希望做什么:

age = 21 // does not work

甚至

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

有可能吗? (更喜欢=方法)

3 个答案:

答案 0 :(得分:4)

你可以这样做:

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

或者这个:

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

但不是这样:

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

如果您覆盖某个功能,则无法更改其返回类型。但是,您可以通过更改签名来重载它。

P.S。请不要这样做:)

答案 1 :(得分:1)

可能的。查看canEqual,hashCode和equals方法。

答案 2 :(得分:1)

使用==,我们可以按照Aleksey's answer中的说明执行此操作(即,使用IntString等的单独方法,而不是Any。我们最接近使用=作为除分配以外的其他内容(基于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