Added the codes used for operator overloading article

This commit is contained in:
Ali Dehghani 2018-11-22 23:07:29 +03:30
parent 1d0fab4252
commit 2ee5e03b88
5 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,27 @@
enum class Currency {
DOLLARS, EURO
}
class Money(val amount: BigDecimal, val currency: Currency) : Comparable<Money> {
override fun compareTo(other: Money): Int =
convert(Currency.DOLLARS).compareTo(other.convert(Currency.DOLLARS))
fun convert(currency: Currency): BigDecimal = TODO()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Money) return false
if (amount != other.amount) return false
if (currency != other.currency) return false
return true
}
override fun hashCode(): Int {
var result = amount.hashCode()
result = 31 * result + currency.hashCode()
return result
}
}

View File

@ -0,0 +1,14 @@
interface Page<T> {
fun pageNumber(): Int
fun pageSize(): Int
fun elements(): MutableList<T>
}
operator fun <T> Page<T>.get(index: Int): T = elements()[index]
operator fun <T> Page<T>.get(start: Int, endExclusive: Int): List<T> = elements().subList(start, endExclusive)
operator fun <T> Page<T>.set(index: Int, value: T) {
elements()[index] = value
}
operator fun <T> Page<T>.contains(element: T): Boolean = element in elements()
operator fun <T> Page<T>.iterator() = elements().iterator()

View File

@ -0,0 +1,14 @@
data class Point(val x: Int, val y: Int)
operator fun Point.unaryMinus() = Point(-x, -y)
operator fun Point.not() = Point(y, x)
operator fun Point.inc() = Point(x + 1, y + 1)
operator fun Point.dec() = Point(x - 1, y - 1)
operator fun Point.plus(other: Point): Point = Point(x + other.x, y + other.y)
operator fun Point.minus(other: Point): Point = Point(x - other.x, y - other.y)
operator fun Point.times(other: Point): Point = Point(x * other.x, y * other.y)
operator fun Point.div(other: Point): Point = Point(x / other.x, y / other.y)
operator fun Point.rem(other: Point): Point = Point(x % other.x, y % other.y)
operator fun Point.times(factor: Int): Point = Point(x * factor, y * factor)
operator fun Int.times(point: Point): Point = Point(point.x * this, point.y * this)

View File

@ -0,0 +1,30 @@
interface View
class TextView(val value: String) : View
class ImageView(val url: String) : View
class UI {
private val views = mutableListOf<View>()
operator fun String.unaryPlus() {
views.add(TextView(this))
}
operator fun View.unaryPlus() {
views.add(this)
}
}
fun ui(init: UI.() -> Unit): UI {
val ui = UI()
ui.init()
return ui
}
fun main(args: Array<String>) {
val header = ui {
+ImageView("http://logo.com")
+"Brand name"
+"Brand description"
}
}

View File

@ -0,0 +1,4 @@
operator fun <T> MutableCollection<T>.plusAssign(element: T) {
add(element)
}
operator fun BigInteger.plus(other: Int): BigInteger = add(BigInteger("$other"))