kotlin语言特性

原文在 https://github.com/Zhuinden/guide-to-kotlin

kotlin的空指针安全相关

?. ?: !! 操作符

class MyAdapter: RecyclerView.Adapter() {
    private var items: List? = null

    fun updateItems(items: List?) {
        this.items = items
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent!!.getContext()).inflate(R.layout.my_item, parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(items!!.get(position))
    }

    override fun getItemCount(): Int {
        return items?.size ?: 0
    }
}

强制类型转换

延迟初始化

private lateinit var realm: Realm

string

val hello: String
    get() = "Hello $name, your overlord ${overlord.name} has been expecting you."

val jsonString = """
        {
            "hello": "world",
            "another": {
                    "field": "field",
                    "boom": "boom"
            }
        }
    """.trimIndent()

data class

data class Dog(
    val name: String,
    val owner: Person
)

@Parcelize
data class LoginKey(val placeholder: String = ""): Parcelable

when关键字

val value = when(number) {
    0,1,2,3,4 -> 1.0
    in 5..9 -> 0.75
    in 10..14 -> 0.5
    in 15..19 -> 0.25
    20 -> 0.2
    else -> 0
}

enum class Colors {
   RED,
   GREEN,
   BLUE
}

val color = Colors.RED

when(color) {
    Colors.RED -> {
       ...
    }
    else ->
       ...
    }
}

控制语句作为表达式(when, return)

val name = tryGetName() ?: return

有名称的参数,默认参数

@JvmOverloads
fun printStrings(first: String = "Hello", second: String = "World") {
    println("$first $second")
}

printStrings()
printStrings("Goodbye", "my dear")
printStrings(first = "Goodbye", second = "my dear")
printStrings(first = "Goodbye")
printStrings(second = "my dear")

如果我们使用了 @JvmOverload 那么在java中也起作用

可变参数和*操作符

java中的可变参数函数是这样的 void dosomething(String... values)

在kotlin中有一种语法实现如下:

fun doSomething(vararg values: String)

如果我们想把这个数组一个一个的传入其他函数,那么就要使用*操作符

fun animateTogether(vararg animators: Animator) = AnimatorSet().apply {
    playTogether(*animators)
}

接口 和默认实现

泛型

fun  findViewById(view: View, @IdRes idRes: Int) = view.findViewById(idRes) as T

val activityType: Class // similar to `? extends T`
    get() = when(this) {
        CAR_HEADER -> CarHeader::class.java
        CAR_VIEW -> CarView::class.java
        DATA_VIEW -> DataView::class.java
    } 
}

val clazz: Class<*> = SomeClass::class.java

你可能感兴趣的:(kotlin语言特性)