主构造器
将构造其放在类的声明后,例如:
data class User constructor(var name:String,var age:Int){
// 其中加上var或者val变量声明关键字,会自动为该类增加同名的属性,不必显示声明
init{
//主构造器无法执行初始化代码,可以在init代码块中执行,kotlin在编译的时候会将init代码块和成员属性的声明按照文件中的上下顺序一起放到构造函数中,因此必须要注意在init代码块中使用的属性的声明要在init代码块之前
}
constructor(name:String, age:Int, gender:Int):this(name,age){
// 类存在主构造器的话,其他构造器必须调用主构造器
}
}
data class
data class表示此类为数据类,实现了hashCode(),toSting(),equals(),copy() 函数,例如:
val user=User("aaa",10,1)
val userCopy=user.copy()
copy方法是重新生成了一个对象,并将原有属性赋值给新对象,
if(userCopy==user)返回的是ture,==调用的是kotlin的user的equals方法,而===才是判断地址的方法
data class的解构:
可以理解为对一个方法返回的数据进一步解析其结构,例如:
fun execute():User{
}
调用execute()函数时,返回的user,如果要使用其中的属性,需要使用user.name,user.age等再次调用其getXXX()函数,而解构可以一步到位
val (name,age,genser)=execute()
简化操作
- 如果response.data为null,则为data赋值为请求失败
var data=response.data?:"请求失败"
- 使用when(if,try-catch)给变量赋值
var color=when(state){
State.ACTIVE->R.color.red
State.PAUSE,State.DESTORY->R.color.gray
}
- arrayList[pos],以数组方式访问列表,这是重写了ArrayList的操作符
- 列表的遍历:
userList.forEach{
if(user.gender==1){
maleList.add(it)
}
}
等价于
val maleList=userList.filter{user.gender==1}
- 数组的循环:
repeat(100){
println(it)
}
for(i in 0..99){
}
for(i in 0 until array.size){ //until不包括右边
}
for(i in array.indices){
}
- 一行直接返回函数:
fun add(a:Int, b:Int)=(a+b)
嵌套函数
kotlin中函数可以嵌套,例如:
fun login(){
fun verify():Boolean{
}
}
verify只能在login函数中被调用,verify函数可以调用login的变量,在每次被调用的时候会生成一个额外对象,要谨慎使用
只可读属性
companion object{
lateinit var currentApplicarion:Context
private set
}
函数参数默认值
调用的时候可以传入单参数,也可以双参数
fun (msg:String, duration:Int=10){
}
扩展函数、属性
扩展函数:
fun Float.dp2px():Float{
return TypedValue.appDimension(TypedValue.COMPLEX_UNIT_DIP,this,displayMetrics)
}
扩展函数是无法覆盖原来的成员函数的
扩展属性:
val ViewGroup.firstChild:View
get()=getChildAt(0)
inline内联函数
inline函数的作用就是通过编译器将函数中的代码复制到调用的地方,减少内存调用栈,增加编译时间,当传入对象是函数时才有意义
class Test{
inline fun setOnCallBackListener(listener : (Test) -> Unit){
var test=Test()
listener().invoke(test)
}
}
fun main(){
val test=Test()
test.setOnCallBackListener(::onCallBack) // 传递的是已经声明的函数
test.setOnCallBackListener( //匿名函数的方式传递
fun (test:Test){
}
)
test.setOnCallBackListener{ // lambda传递函数
}
}
fun onCallBack(test:Test){
}
inline和泛型结合可直接拿到泛型的class:
fun create(clazz:Class):T{
return RETROFIT.create(clazz)
}
fun main(){
create(API::class.java)
}
可改为:
inline fun create():T{
return RETROFIT.create(T::class.java)
}
fun main(){
create()
}
抽象属性
by lazy:代码块只有第一次调用person时才会调用一次
interface BaseView{
val person:T
}
class RoundView :BaseView{
override val person:Man by lazy{
Man("aaa",10,1)
}
}
by:属性委托
var token by Saver("token")
class Saver(var token: String) {
operator fun getValue(test: Test, property: KProperty<*>): Any {
CacheUtils.get(token)!!
}
operator fun setValue(test: Test, property: KProperty<*>, any: Any) {
CacheUtils.save(token,value)
}
}
内置标准函数,作用域函数
Kotlin中的闭包:
作用域函数 | 指代对象 | 返回值 |
---|---|---|
let(let it last line) | it | 返回最后一行,若最后一行语句无返回值,则整个let语句块也无返回值,常用语空判断 |
run(run this last line) | this | 返回最后一行 |
also(also it self) | it | 返回调用对象本身 |
apply(apply this self) | this | 返回调用对象本身 |
with不是一个扩展函数,使用时:
val user:User = User("aaa", 10)
with(user){
println(this)
this!!.buy(50) //将空判断放在了with方法内部
println(this)
}