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

:: Gson 解析
data class LoginInfo(id,name,user,loginName)

val (_,id, _, loginName) 
= Gson().fromJson(“”,LoginInfo::class.java) as LoginInfo
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章