Android鬼点子-关于kotlin的几招祖传手艺

1,516 阅读2分钟

图1 kotlin用上之后就戒不了啦!!!

1.稍后初始化

lateinit var modelHolder: ModelHolder

使用lateinit关键字,可以稍后初始化。

val name: String by lazy { "sherlbon" }

用到时候,再初始化。

2.使用类方法,类变量

在java中使用static关键字声明类方法和类变量。

kotlin中使用companion object声明类方法和类变量。

companion object {
        var retrofit = Retrofit.Builder()
                .baseUrl(AppConfig.HttpConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(getOkHttpClient())
                .build()
                }

注意如果需要在java也能调用到,需要增加@JvmField修饰变量和@JvmStatic修饰方法。

3.直接实现接口

在java中我们经常使用new 接口名{}来直接实现一个接口对象。

onWeiboChangedListener listener = new onWeiboChangedListener() {
				@Override
				public void onWeiboChanged(Weibo weibo) {
				···
				}
			};

在kotlin中使用object:接口名{}

var listener = object : onWeiboChangedListener {
                override fun onWeiboChanged(weibo: Weibo) {
                ···
                }
            }

4.实体类

data class entity_null_obj(var s1: String,var s2: String)

5.循环查找

val person = personList.find { it.id == somePersonId }

val 声明常量,会遍历personList,it代表每个成员。

循环遍历 selected.forEach {it}

过滤 val positiveNumbers = list.filter { it > 0 }

你还可以这样:

persons
  .filter { it.age >= 18 }
  .sortedBy { it.name }
  .map { it.email }
  .forEach { print(it) }

6.this和return

如果用到调用者,可以指定this@MainActivitythis@Listener

可以用return@forEach指定返回的目标,@后面可以有很多可以指定。

7.判断类型

if (obj is Invoice){
        obj.calculateTotal()
        }

8.?和!!

?的作用是告诉程序这里可能是null。程序这里会自动判断,如果是null就不会继续执行导致抛出异常。

!!的作用是告诉程序这里绝不可能是null。

9.键值对

val data = mapOf(1 to "one", 2 to "two")

10.扩展方法

fun Context.toast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()

给Context对象增加了toast()方法。这句代码可以写在程序中的任何位置。

11.再也不用findViewById

直接用控件id引用。可以对butterknife说再见了。

12.字符串差值

val x = 4
val y = 7
print("sum of $x and $y is ${x + y}")  // sum of 4 and 7 is 11

13.参数随便玩

//默认参数
fun build(title: String, width: Int = 800, height: Int = 600) {
    Frame(title, width, height)
}

//可以通过参数名传递参数
build("PacMan", 400, 300)                           // equivalent
build(title = "PacMan", width = 400, height = 300)  // equivalent
build(width = 400, height = 300, title = "PacMan")  // equivalent

14.这就是你想要的相等

val john1 = Person("John")
val john2 = Person("John")

john1 == john2    // true  (structural equality)
john1 === john2   // false (referential equality)

可以用==替代equal了。

15.升级后的switch

val res: Boolean = when (x) {
    1 -> true
    2 -> false
    3, 4 -> true
    in 5..10 -> true
    is String -> true
    else -> throw IllegalStateException()
}

可以直接取到返回值。

16.线程切换

doAsync {
        val url = "https://www.baidu.com/"
        val result = URL(url).readText()
        uiThread{
            Log.e("TAg", result)
        }
    }

结合Anko,Anko中有很多很方便的扩展。

17.属性观察

import kotlin.properties.Delegates

class User {
    var name: String by Delegates.observable("张三") {
        prop, old, new ->
        println("old:$old -> new:$new")
    }
}

fun main(args: Array<String>) {
    val user = User()
    user.name = "李四"
    user.name = "王二麻子"
}

输出:

old:张三 -> new:李四
old:李四 -> new:王二麻子