data class Point(val x: Int, val y: Int) {operator fun plus(other: Point): Point {return Point(x + other.x, y + other.y)}}val p1 = Point(10, 20)val p2 = Point(30, 40)println(p1 + p2) //Point(x=40, y=60)
operator fun Point.plus(other: Point): Point {return Point(x + other.x, y + other.y)}
表达式 | 函数名 |
a * b | times |
a / b | div |
a % b | mod |
a + b | plus |
a - b | minus |
operator fun Point.times(scale: Double): Point {return Point((x * scale).toInt(), (y * scale).toInt())}val p = Point(10, 20)print(p * 1.5) //Point(x=15, y=30)
Kotlin运算符不会自动支持交换性。如果希望用户能够使用15*p以外,还能使用p*1.6,你需要为它定义个单独的运算符:
operator fun Double.times(p:Point):Point{return Point((p.x * this).toInt(), (p.y * this).toInt())}
operator fun Char.times(count: Int): String {return toString().repeat(count)}println('a' * 3) //aaa
operator fun Point.unaryMinus():Point{return Point(-x,-y)}val p = Point(10,20)println(-p)
表达式 | 函数名 |
+a | unaryPlus |
-a | unaryMinus |
!a | not |
++a,a++ | inc |
--a,a-- | dec |
operator fun BigDecimal.inc() = this +BigDecimal.ONEvar bd = BigDecimal.ZEROprintln(bd++) //0println(++bd) //2
data class Point(val x: Int, val y: Int) {override fun equals(other: Any?): Boolean {//这里使用了恒等运算符===来检查参数与调用equals的对象是否相同。恒等运算符与Java中的==运算符//是完全相同的;===运算符不能被重载if (other === this) return trueif (other !is Point) return falsereturn other.x == x && other.y == y}}println(Point(10,20)==Point(10,20)) //trueprintln(Point(10,20)!=Point(5,5)) //trueprintln(null == Point(1,2)) //false
class Person(val firstName: String, val lastName: String) : Comparable<Person> {override fun compareTo(other: Person): Int {return compareValuesBy(this, other, Person::lastName, Person::firstName)}}
operator fun Point.get(index: Int): Int {return when (index) {0 -> x1 -> yelse ->throw IndexOutOfBoundsException("Invalid coordinate $index")}}val p = Point(10,20)println(p[1]) //20
operator fun MutablePoint.set(index: Int, value: Int) {when (index) {0 -> x = value1 -> y = valueelse ->throw IndexOutOfBoundsException("Invalid coordinate $index")}}val p = MutablePoint(10, 20)p[1] = 42println(p) //MutablePoint(x=10, y=42)
in运算符,用于检查某个对象是否属于集合。相应的函数叫做contains
。
data class Rectangle(val upperLeft:Point,val lowerRight:Point)operator fun Rectangle.contains(p:Point):Boolean{return p.x in upperLeft.x until lowerRight.x &&p.y in upperLeft.y until lowerRight.y}val rect = Rectangle(Point(10,20),Point(50,50))println(Point(20,30) in rect) //trueprintln(Point(5,5) in rect) //false
val now = LocalDate.now()val vacation = now..now.plusDays(10)println(now.plusWeeks(1) in vacation) //trueval n = 9println(0..(n+1)) //0..10(0..n).forEach(::print) //0123456789
operator fun ClosedRange<LocalDate>.iterator(): Iterator<LocalDate> =object : Iterator<LocalDate> {var current = startoverride fun hasNext() = current <= endInclusiveoverride fun next() = current.apply {current = plusDays(1)}}val newYear = LocalDate.ofYearDay(2017, 1)val daysOff = newYear.minusDays(1)..newYearfor (dayOff in daysOff) {println(dayOff)}// 2016-12-31// 2017-01-01