1.背景
当kotlin中声明需要传入一个返回值为空(Unit)的方法引用.
代码示例:
下方第二个参数为一个方法引用,(参数为BiometricPrompt.AuthenticationResult, 返回类型为Unit).
object BiometricPromptUtil {
private const val TAG = "BiometricPromptUtil"
fun createBiometricPrompt(
activity: AppCompatActivity,
processSuccess: (BiometricPrompt.AuthenticationResult) -> Unit
): BiometricPrompt {
val executor = ContextCompat.getMainExecutor(activity)
val callback = object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errCode: Int, errString: CharSequence) {
super.onAuthenticationError(errCode, errString)
Log.d(TAG, "errCode is $errCode and errString is: $errString")
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
Log.d(TAG, "User biometric rejected.")
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
Log.d(TAG, "Authentication was successful")
processSuccess(result)
}
}
return BiometricPrompt(activity, executor, callback)
}
}
2. kotlin调用传参
如果调用方是kotlin代码示例, 只需要直接定义一个默认返回为Unit的函数并将其传入即可.
private fun showBiometricPromptForEncryption() {
val canAuthenticate = BiometricManager.from(applicationContext).canAuthenticate()
if (canAuthenticate == BiometricManager.BIOMETRIC_SUCCESS) {
val secretKeyName = getString(R.string.secret_key_name)
cryptographyManager = CryptographyManager()
val cipher = cryptographyManager.getInitializedCipherForEncryption(secretKeyName)
val biometricPrompt =
BiometricPromptUtils.createBiometricPrompt(this, ::encryptAndStoreServerToken) //重点关注第二个参数
val promptInfo = BiometricPromptUtils.createPromptInfo(this)
biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
}
}
private fun encryptAndStoreServerToken(authResult: BiometricPrompt.AuthenticationResult) { // 用于做形参的函数,函数返回类型是默认的Unit.
authResult.cryptoObject?.cipher?.apply {
SampleAppUser.fakeToken?.let { token ->
Log.d(TAG, "The token from server is $token")
val encryptedServerTokenWrapper = cryptographyManager.encryptData(token, this)
cryptographyManager.persistCiphertextWrapperToSharedPrefs(
encryptedServerTokenWrapper,
applicationContext,
SHARED_PREFS_FILENAME,
Context.MODE_PRIVATE,
CIPHERTEXT_WRAPPER
)
}
}
finish()
}
3.Java调用传参
但是如果是在java环境中调用传入函数形参,该函数该如何声明呢?
直接声明一个返回为void的函数,并传入行不行? 答案是不行的. 报错如下:
Bad return type in lambda expression: void cannot be converted to Unit
解决方案,直接以lambda以形式传入,多加一个return null, 多封装一层.