Kotlin骚气写法 四

Volatile 单例
// For Singleton instantiation
@Volatile private var instance: String? = null
synchronized 同步锁
instance ?: synchronized(this) {
  instance ?: ""
}
:: 的函数使用
fun test(){
	  val numbers = listOf(1, 2, 3)
        println(numbers.filter(::isOdd)) // 
        println(numbers.filter { isOdd(it) }) // 
        println(numbers.filter { isOdd(x = it) })
}

fun isOdd(x: Int) = x % 2 != 0

这里的 isOdd 不需要在同一个类中

还有这种骚操作?

fun test(){
	val get = ::isEmptyStringList.get()
	
	get.invoke(numbers)
	//简化后  不加::还调不动
	::isEmptyStringList.get().invoke(numbers)
} 

val isEmptyStringList: List<Int>.() -> Boolean = List<Int>::isEmpty

发布了141 篇原创文章 · 获赞 40 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/qq_20330595/article/details/94392259