为什么我们要 'get a stable reference' in Kotlin/Android?
Why should we 'get a stable reference' in Kotlin/Android?
我正在阅读 Android CameraX 代码实验室:https://codelabs.developers.google.com/codelabs/camerax-getting-started#4
简化后的代码片段是这样的:
class MainActivity : AppCompatActivity() {
private var imageCapture: ImageCapture? = null
//(some other codes here...)
private fun takePhoto() {
// Get a stable reference of the modifiable image capture use case
val imageCapture = imageCapture ?: return
//(some other codes here...)
}
}
在代码实验室中,它说:
First, get a reference to the ImageCapture use case.
为什么我们需要 takePhoto()
中的新引用 imageCapture
?
我们不能只使用 MainActivity
中的 imageCapture
吗?
这是为了某种 'best practice' 的东西还是我遗漏了什么?
如有任何建议,我们将不胜感激!
它相当于空检查。
stable reference -> Not null reference
类似于
if(imageCapture==null) return;
他们也在代码实验室中提到了同样的事情。
First, get a reference to the ImageCapture use case. If the use case is null, exit out of the function. This will be null If you tap the photo button before image capture is set up. Without the return statement, the app would crash if it was null.
所以基本上你是在消除 NPE 的可能性,它可以通过多种方式完成,而他们恰好为此使用了另一个局部变量。也可以用 let
.
来完成
imageCapture?.let{
// code goes here
}
private var imageCapture: ImageCapture? = null
在这一行中,您为 imageCapture 变量分配了空值。现在,当您开始使用 takePhoto() 时,编译器将如何知道 imageCapture 不再为空?
如@ADM 所述,您可以使用
imageCapture?.let{
//your code goes here
}
如果你愿意。这基本上是确保您不会在可为 null 的对象上调用任何内容。
我正在阅读 Android CameraX 代码实验室:https://codelabs.developers.google.com/codelabs/camerax-getting-started#4
简化后的代码片段是这样的:
class MainActivity : AppCompatActivity() {
private var imageCapture: ImageCapture? = null
//(some other codes here...)
private fun takePhoto() {
// Get a stable reference of the modifiable image capture use case
val imageCapture = imageCapture ?: return
//(some other codes here...)
}
}
在代码实验室中,它说:
First, get a reference to the ImageCapture use case.
为什么我们需要 takePhoto()
中的新引用 imageCapture
?
我们不能只使用 MainActivity
中的 imageCapture
吗?
这是为了某种 'best practice' 的东西还是我遗漏了什么?
如有任何建议,我们将不胜感激!
它相当于空检查。
stable reference -> Not null reference
类似于
if(imageCapture==null) return;
他们也在代码实验室中提到了同样的事情。
First, get a reference to the ImageCapture use case. If the use case is null, exit out of the function. This will be null If you tap the photo button before image capture is set up. Without the return statement, the app would crash if it was null.
所以基本上你是在消除 NPE 的可能性,它可以通过多种方式完成,而他们恰好为此使用了另一个局部变量。也可以用 let
.
imageCapture?.let{
// code goes here
}
private var imageCapture: ImageCapture? = null
在这一行中,您为 imageCapture 变量分配了空值。现在,当您开始使用 takePhoto() 时,编译器将如何知道 imageCapture 不再为空?
如@ADM 所述,您可以使用
imageCapture?.let{
//your code goes here
}
如果你愿意。这基本上是确保您不会在可为 null 的对象上调用任何内容。