先来一个demo
data class Point(val x:Int,val y:Int) {
operator fun plus(other:Point):Point{
return Point(x+other.x,y+other.y)
}
}
fun main(args: Array<String>) {
val p1=Point(1,6)
val p2=Point(7,334)
println(p1+p2)
}
结果:Point(x=8, y=340)
重载运算符:
a*b 函数名:times
a/b 函数名:div
a%b 函数名:mod
a+b 函数名:plus
a-b 函数名:minus
特殊运算符
shl——带符号左移
shr——带符号右移
ushr——无符号右移
and——按位与
or——按位或
xor——按位异或
inv——按位取反
一元运算符
+a unaryPlus
+b unaryMinus
!a not
++a,a++ inc
--a,a-- dec
forEach一种写法:
(0..n).forEach{ println(it)}
直接:
val n=9
println(0..(n+1))
结果不会遍历,而是:0..10
解构函数:
val (x,y)=p1;
println(x)
data class Test1(val name:String,val extension:String)
fun splitFileName(fullName:String):Test1{
val result=fullName.split('.',limit = 2)
return Test1(result[0],result[1])
}
fun main(args: Array<String>) {
val (name,external )= splitFileName("ddfeweweww.ttyuiii")
println(name)
}
接口监听:
class Person (val name :String,age : Int ,salary :Int): PropertyChangeAware() {
var age:Int =age
set(newValue){
val oldValue=field
field=newValue
changeSupport.firePropertyChange("age",oldValue,newValue)
}
var salary:Int =salary
set(newValue){
val oldValue=field
field=newValue
changeSupport.firePropertyChange("salary",oldValue,newValue)
}
}
open class PropertyChangeAware{
protected val changeSupport=PropertyChangeSupport(this)
fun addPropertyyChangeListener(listener:PropertyChangeListener){
changeSupport.addPropertyChangeListener(listener)
}
fun removePropertyChangeListenerListener(listener: PropertyChangeListener){
changeSupport.removePropertyChangeListener(listener)
}
}
val p=Person("dsdsf",23,500)
p.addPropertyyChangeListener(
PropertyChangeListener {
evt -> println("Property ${evt.propertyName} changed from ${evt.oldValue} to ${evt.newValue}" )
}
)
p.age=35
网友评论