markdown Kotlin扩展功能和属性警告

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Kotlin扩展功能和属性警告相关的知识,希望对你有一定的参考价值。

*Source:* [StackOverflow](https://stackoverflow.com/a/40599649), [jlelse](https://android.jlelse.eu/the-ugly-truth-about-extension-functions-in-kotlin-486ec49824f4), [JetBrains](https://youtrack.jetbrains.com/oauth?state=%2Fissue%2FKT-11968)

**Question:** Since Kotlin extension functions and properties are areally static methods and properties, is using them bad practice?

**Answer:**

It depends on how you wrote extension function/property. If they doesn't edit or access shared state i.e. if property and function is clear function: it absolutely not bad practice.

Example 1:

```kotlin
fun String.countSpaces(): Int {
    return this.count { c -> c == ' ' }
}
```

This functions works perfectly in multi-threaded environment, since String is immutable.

Example 2:

```kotlin
data class MutablePerson(val name: String, var speech: String)

fun MutablePerson.count(nextNumber: Int) {
    this.speech = "${this.speech} ${nextNumber}"
}
```

This function mutates `speech` property of `MutablePerson` object and assign operation is not atomic. If `count` will be called on one object from different threads - inconsistent state possible.

Example:

```kotlin
fun main(args: Array<String>) {
    val person = MutablePerson("Ruslan", "I'm starting count from 0 to 10:")

    (1..10).forEach { it ->
        Thread({
            person.count(it)
            println(person.speech)
        }).start()
    }

    Thread.sleep(1000)

    println(person.speech)
}
```

Possible output:

```
I'm starting count from 0 to 10: 1
I'm starting count from 0 to 10: 1 3
I'm starting count from 0 to 10: 1 3 4
I'm starting count from 0 to 10: 1 3 4 2
I'm starting count from 0 to 10: 1 3 4 2 5
I'm starting count from 0 to 10: 1 3 4 2 5 8
I'm starting count from 0 to 10: 1 3 4 2 5 6
I'm starting count from 0 to 10: 1 3 4 2 5 6 7
I'm starting count from 0 to 10: 1 3 4 2 5 6 7 9
I'm starting count from 0 to 10: 1 3 4 2 5 6 7 9 10
I'm starting count from 0 to 10: 1 3 4 2 5 6 7 9 10
```

So extension functions and extensions properties not bad practice, they are just like properties and method in classes: depending on how you wrote they thread safe or not.

Read the second link for further detail on another shortage of extension functions and properties, but in short, as of Kotlin 1.1.60, extension function and property are not applicable for Java and Android classes.

以上是关于markdown Kotlin扩展功能和属性警告的主要内容,如果未能解决你的问题,请参考以下文章

Kotlin入门(33)运用扩展属性

如何禁用 Kotlin Android 扩展插件生成合成视图属性

漫画:Kotlin 的扩展细节探究 | 鉴赏 Kotlin 的语言艺术!

Kotlin Vocabulary | 使用 Kotlin 中的扩展提升代码可读性

Kotlin扩展函数总结 ★ ( 超类扩展函数 | 私有扩展函数 | 泛型扩展函数 | 扩展属性 | 定义扩展文件 | infix 关键字用法 | 重命名扩展函数 | 标准库扩展函数 )

Kotlin扩展函数总结 ★ ( 超类扩展函数 | 私有扩展函数 | 泛型扩展函数 | 扩展属性 | 定义扩展文件 | infix 关键字用法 | 重命名扩展函数 | 标准库扩展函数 )