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扩展功能和属性警告的主要内容,如果未能解决你的问题,请参考以下文章