Like this
a == b
or like this
a.equals(b)
The docs seem to imply the first way but only the second way passes my test.
a == b
a.equals(b)
class Thing
cue init(i as int)
base.init
_i = i
pro i from var as int
# Cobra will invoke a strongly typed .equals method
# for == and <> between two statically typed things:
def equals(other as Thing) as bool
return other.i == .i
# Override Object.equals
# Cobra will use this in dynamic situations
# and the .NET libs may use this in others,
# such as using Thing as a key in a dictionary:
def equals(obj as Object?) as bool is override
if obj inherits Thing, return .equals(obj)
return false
# When you override Object.equals, you should override:
def getHashCode as int is override
return .i.getHashCode
class Program
def main
assert Thing(5) == Thing(5)
assert Thing(5) <> Thing(2)
# cobra --version
# Cobra svn:2683 (post 0.8) / 2012-06-01 on Mono 2.10.8.1 CLR v4.0.30319 on Ubuntu 12.04 LTS
# cobra eq_test.cobra
class Thing
cue init(i as int)
base.init
_i = i
pro i from var as int
def equals(other as Thing) as bool
return other.i == .i
class Program
def main
assert Thing(5) == (Thing(5))
assert Thing(5) <> (Thing(2))
class Foo
cue init(i as int, s as String)
base.init
_i, _s = i, s
pro i from var as int
pro s from var as String
# Cobra will invoke a strongly type .equals method
# for == and <> between two statically typed objects:
def equals(other as Foo) as bool
return other.i == .i and other.s == .s
# Override Object.equals
# Cobra will use this in dynamic situations
# and the .NET libs may use this in others,
# such as using Foo as a key in a dictionary:
def equals(obj as Object?) as bool is override
if obj inherits Foo, return .equals(obj)
return false
# When you override Object.equals, you should override .getHashCode:
def getHashCode as int is override
return HashCodeUtils.combine(.i.getHashCode, .s.getHashCode)
class Program
def main
assert Foo(5, 'foo') == Foo(5, 'foo')
assert Foo(5, 'foo') <> Foo(2, 'foo')
nerdzero wrote:...
However, based on what you've described, shouldn't the following code work since it would invoke the strongly typed equals?
...
class Thing
cue init(i as int)
base.init
_i = i
pro i from var as int
# def equals(other as Thing) as bool
# return other.i == .i
def compareTo(other as Thing) as int
return .i - other.i
class Program
def main
assert Thing(5) == Thing(5)
assert Thing(5) <> Thing(2)
class Thing
cue init(i as int)
base.init
_i = i
pro i from var as int
def compareTo(other as Thing) as int
return .i - other.i
class Program
def main
things = List<of Thing>()
things.add(Thing(5))
assert Thing(5) in things #this will fail
Users browsing this forum: No registered users and 33 guests