-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOperatorOverload.kt
More file actions
41 lines (36 loc) · 1 KB
/
Copy pathOperatorOverload.kt
File metadata and controls
41 lines (36 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package tutorial
fun main(args: Array<String>){
var blocks1 = Blocks(1)
val blocks2 = Blocks(2)
println("blocks1: $blocks1")
println("++blocks1: ${++blocks1}")
println("blocks1 ($blocks1) + blocks2 ($blocks2): ${blocks1 + blocks2}")
println("blocks1 plus blocks2: ${blocks1 plus blocks2}") // due to using 'infix' identifier
}
class Blocks (var count: Int = 0){
/**
* Return count '#' as a symbol of blocks
*/
override fun toString(): String {
var string = ""
(1..count).forEach { string += "#" }
return string
}
/**
* Add two blocks (block1 + block2)
* See the full list of available operators to overload
* <a href="https://kotlinlang.org/docs/reference/operator-overloading.html">here</a>
*/
infix operator fun plus(other: Blocks) : Blocks{
val newBlocks = Blocks()
newBlocks.count = this.count + other.count
return newBlocks
}
/**
* Increment a block (++block or block++)
*/
operator fun inc() : Blocks{
count++
return this
}
}