1: одноэлементный режим
2: Цикл
=====================【Один случай 1 】====================
======【Один случай 1 】
class SingleInstanceOne private constructor() {
private object SingleHolder {
val INSTANCE = SingleInstanceOne()
}
companion object {
fun getInstance() =
SingleHolder.INSTANCE
}
}
=====【Один случай 2 】
class SingleInstanceTwo private constructor() {
companion object {
val INSTANCE: SingleInstanceTwo by lazy {
SingleInstanceTwo()
}
}
}
=====【Один случай 3 с параметрами 】
class SingleInstanceThere private constructor(context: Context) {
init {
// do init
}
open class SingletonHolder<out T : Any, in A>(private val creator: (A) -> T) {
private var instance: T? = null
fun getInstance(arg: A): T =
instance ?: synchronized(this) {
instance ?: creator(arg).apply {
instance = this
}
}
}
companion object : SingletonHolder<SingleInstanceThere, Context>(::SingleInstanceThere)
fun doSomething() {
}
}
=====================【Цикл 】=====================
======【Цикл 1 】
// 打印:1 到 10
for (index in 1..10) {
Timber.tag(TAG).d("test1() $index")
}
======【Цикл 2 】
// 打印:1 到 9
for (index in 1 until 10) {
Timber.tag(TAG).d("test1() $index")
}
======【Цикл 3 】
// 倒序 输出 10,9,8...1
for (index in 10 downTo 1) {
Timber.tag(TAG).d("$index")
}
======【Петля 4 】
// 输出 1.3.5.7.9
for (index in 1..10 step 2) {
Timber.tag(TAG).d("$index")
}
// 输出 1.4.7.10
for (index in 1..10 step 3) {
Timber.tag(TAG).d("$index")
}
======【Петля 5 】
private val list = arrayListOf<String>("0", "1", "2", "3", "4")
private fun test5() {
// 输出 0 1 3
for ((index, item) in list.withIndex()) {
if (index == 2) continue
if (index == 4) break
Timber.tag(TAG).d("$item")
}
}
======【Петля 6 】
val list = arrayListOf<String>("0", "1", "2", "3", "4")
// 输出 0 1
loop@ for ((index, item) in list.withIndex()) {
if (index == 2) {
break@loop
}
Timber.tag(TAG).d("$item")
}
// 输出 1 11 12
loop@ for (index in 1..10) {
Timber.tag(TAG).d("$index")
for (item in 11..20) {
if (item == 13) {
break@loop
}
Timber.tag(TAG).d("$item")
}
}
======【Цикл 7 】
private val list = arrayListOf<String>("0", "1", "2", "3", "4")
private fun test7() {
// 输出 0 1 3 4
list.forEach list@{
if (it == "2") {
return@list
}
Timber.tag(TAG).d("$it")
}
}
======【Цикл 8 】
private val list = arrayListOf<String>("0", "1", "2", "3", "4")
private fun test8() {
// 输出 0 1 3 4
list.forEachIndexed { index, s ->
if (index == 2) return@forEachIndexed
Timber.tag(TAG).d("$s")
}
// 输出 0 1
run outSide@{
list.forEachIndexed { index, s ->
if (index == 2) return@outSide
Timber.tag(TAG).d("$s")
}
}
}
====================【Обратный вызов 】=====================
// inline是修饰内联方法,有lambda 参数都应该加一下内联方法修饰,提高效率
private inline fun request(call: () -> Unit) {
}
private inline fun request2(call: (code: Int, msg: String) -> Unit) {
}
private inline fun request3(par: String, call: (code: Int, msg: String) -> Unit) {
}
//使用
request {
}
request2 { code, msg ->
}
request3("") { code: Int, msg: String ->
}