这取决于您如何编写扩展函数/属性。如果他们不编辑或访问共享状态,即如果属性和功能是明确的功能:这绝对不是坏习惯。
示例 1:
fun String.countSpaces(): Int {
return this.count { c -> c == ' ' }
}
此函数在多线程环境中完美运行,因为String 是不可变的。
示例 2:
data class MutablePerson(val name: String, var speech: String)
fun MutablePerson.count(nextNumber: Int) {
this.speech = "${this.speech} ${nextNumber}"
}
这个函数改变了MutablePerson对象的speech属性并且赋值操作不是原子的。如果 count 将在不同线程的一个对象上调用 - 可能出现不一致的状态。
例子:
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)
}
可能的输出:
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
所以扩展函数和扩展属性是不错的做法,它们就像类中的属性和方法:取决于你如何编写它们是否线程安全。