前言
在以前,我们对时间加减是这样操作的。
println(LocalDateTime.now().plusDays(1))
println(LocalDateTime.now().minusDays(1))
而在Kotlin中,只要稍作修改,就可以写出这样的。
infix fun Int.天(type: String): LocalDateTime {
if ("前" == type) return LocalDateTime.now().minusDays(this.toLong())
if ("后" == type) return LocalDateTime.now().plusDays(this.toLong())
return LocalDateTime.now()
}
fun main() {
println(3 天 "前")
println(3 天 "后")
}
怎么样,处理时间从来没有这么直观过吧?
如果在加一点规范化,我们可以把参数写成一个枚举类型。
enum class Day {
前, 后
}
infix fun Int.天(type: Day): LocalDateTime {
if (type == Day.前) return LocalDateTime.now().minusDays(this.toLong())
if (type == Day.后) return LocalDateTime.now().plusDays(this.toLong())
throw IllegalArgumentException("参数错误")
}
fun main() {
println(3 天 Day.前)
println(3 天 Day.后)
}
infix函数
这种写法在kotlin中被称为中缀函数,这个函数最终会被编译为static LocalDateTime 天(arg1,arg2)。
可以看到有两个参数:
arg1是作用于类型的参数值,如上面的例子,我们只作用于Int类型,那么arg1则是具体的Int值,
arg2则是我们真正的参数。
在中缀函数中,this不在表示本类的引用,而是arg1参数。
获取时间指定字段
利用中缀函数换一种获取年月日的写法。
enum class TimeField{
年,月,日,时,分,秒
}
infix fun String.取(field: TimeField): Int {
val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val localDateTime = LocalDateTime.parse(this, dateTimeFormatter)
if (field == TimeField.年) return localDateTime.year
if (field == TimeField.月) return localDateTime.monthValue
if (field == TimeField.日) return localDateTime.dayOfMonth
throw IllegalArgumentException("参数错误")
}
fun main() {
println("2022-08-18 10:52:52" 取 TimeField.年)
}
自定义操作符
我们还可以自定义操作符,以便于我们可以在时间上进行+、-操作,如下
operator fun LocalDateTime.plus(day: Long): LocalDateTime {
return this.plusDays(day)
}
operator fun LocalDateTime.minus(day: Long): LocalDateTime {
return this.minusDays(day)
}
fun main() {
println(LocalDateTime.now() + 2)
println(LocalDateTime.now() - 2)
}
还可以进行++、--操作。
operator fun LocalDateTime.inc(): LocalDateTime {
return this.plusDays(1)
}
operator fun LocalDateTime.dec(): LocalDateTime {
return this.minusDays(1)
}
fun main() {
var now = LocalDateTime.now()
println(++now)
println(--now)
}
时间比较
如果对时间进行比较,kotlin默认已经为我们写好了operator函数,可以直接操作。
operator fun LocalDateTime.plus(day: Long): LocalDateTime {
return this.plusDays(day)
}
fun main() {
var now = LocalDateTime.now()
println((now + 3 ) <= LocalDateTime.now())
}
operator函数
一般我们只能对数字类型进行++、--等,而kotlin可以让我们对任何一种类型进行任何操作符运算。
如下是一些常用的写法。
| 表达 | 翻译 |
|---|---|
+a | a.unaryPlus() |
-a | a.unaryMinus() |
!a | a.not() |
a++ | a.inc() |
a-- | a.dec() |
a + b | a.plus(b) |
a - b | a.minus(b) |
a * b | a.times(b) |
a / b | a.div(b) |
a % b | a.rem(b) |
a..b | a.rangeTo(b) |
a in b | b.contains(a) |
a !in b | !b.contains(a) |
a += b | a.plusAssign(b) |
a -= b | a.minusAssign(b) |
a *= b | a.timesAssign(b) |
a /= b | a.divAssign(b) |
a %= b | a.remAssign(b) |
示例
class User {
var age = 2
}
operator fun User.plus(value: Int) {
this.age += value
}
fun main() {
var user = User()
user + 3
println(user.age)
}
比较简单,就不演示了