异步一次回调变同步直接返回

suspendCoroutine

适用于一次一次调用一次返回结果,返回值用cont.resume返回;错误的情况通过cont.resumeWithException抛异常出去.注意这是个挂起方法.

suspend fun purchase() = suspendCoroutine<String> { cont ->

    helper.setListenner(object:Listenner{
        override fun onResult(result){
            if(result != null) cont.resume(result)
            else cont.resumeWithException(Exception())
        }
    })
    helper.exe()

}

kotlin奇技淫巧

一个list转化成另一个list

            val newlist = list.flatMap {
                listOf(RemoteBanner(it))
            }

it表示迭代器的每一个元素

从集合里根据条件查找第一个结果元素

返回第一个匹配到的元素

list.find { it.key == key }

kotlin let、also区别

class A {
        val b:B=null
        fun test() {
            b.let{}
            b.also{}
        }
    }
function it this 说明
let 调用者即b 所属类即A 可以自定义返回值,即最后一行代码
also 调用者即b 所属类即A 不能自定义返回值,程序自动返回this

蓝牙不需要用户确认的配对方式

        registerReceiver(blePairBroadcastReceiver, IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST))




class BlePairBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action == BluetoothDevice.ACTION_PAIRING_REQUEST) { try { val device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice val pin = intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 1234) //the pin in case you need to accept for an specific pin Log.d("BleActivity", "Start Auto Pairing. PIN = " + intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 1234)) val pinBytes: ByteArray pinBytes = ("" + pin).toByteArray(charset("UTF-8")) device.setPin(pinBytes) //setPairing confirmation if neeeded device.setPairingConfirmation(true) } catch (e: Exception) { Log.e("BleActivity", "Error occurs when trying to auto pair") e.printStackTrace() } } } }

kotlin Require and check

Are your function arguments valid? Check before using them, with require. If they’re not valid an IllegalArgumentException is thrown.

require代替check然后抛异常

fun setName(name: String) {
  // calling setName(“”) throws IllegalArgumentException
  require(name.isNotEmpty()) { “Invalid name” }

  // …
}