HadesLang Doc
Search…
Operator overloading
All operator in Hades can be overloaded. The syntax for this is similar to overloading an inherited function. Operator overloading in Hades always assumes a right operation so the base for the operation is always the parameter on the left.

Example

1
with console from std:io
2
3
class Vector
4
var x = 0
5
var y = 0
6
var z = 0
7
8
func Vector(x,y,z)
9
this.x = x
10
this.y = y
11
this.z = z
12
end
13
14
func! toString()
15
put "{},{},{}".format(x,y,z)
16
end
17
18
func! op+(v)
19
if(v is int)
20
put Vector(x+v,y+v,z+v)
21
else if(v is Vector)
22
put Vector(x + v.x, y + v.y, z + v.z)
23
end
24
25
put null
26
end
27
end
28
29
var v1 = Vector(1,2,3)
30
var v2 = Vector(4,5,6)
31
32
var v3 = v1 + v2 //overloaded operator is called on v1
33
console.out(v3) //outputs: 5,7,9
Copied!

Index operator overloading

One special case of operator overloading is when you want to overload the index operator [].
There are two functions that can be overwritten:
  • reading from an index: index(args indices)
  • writing to an index: index(args indicies, newValue)

Example

1
class MyWayCoolerMapImplementation
2
private let map = Map()
3
4
func! index(args indices)
5
if (indices.length is 1)
6
let index = indices[0]
7
put map.get(index)
8
end
9
10
raise ArgumentError()
11
end
12
13
func! index(args indices, newValue)
14
if (indices.length is 1)
15
let index = indices[0]
16
map.put(index, newValue)
17
end
18
19
raise ArgumentError()
20
end
21
end
Copied!
Last modified 2yr ago