将 lateinit var 设置为 null 不起作用-但在示例中的 Google 文档中

Set lateinit var to null doesnt work - But in Googles Documentation its in the example

所以我想在我的 android 应用程序中创建一个插页式广告,但他们的示例不起作用(对我来说?)。

他们在那里将值 mIntersitialAd 设置为 null,但它是 lateinit var,因此应该不可能。我是不是遗漏了什么,或者真的有可能吗?

Link 到文档:

Interstitial Ad

代码示例:

import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;

class MainActivity : AppCompatActivity() {
  
    private lateinit var mInterstitialAd:InterstitialAd
    private final var TAG = 'MainActivity'
  
    override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      

      var adRequest = AdRequest.Builder().build()

      InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest, object : InterstitialAdLoadCallback() {
        override fun onAdFailedToLoad(adError: LoadAdError) {
          Log.d(TAG, adError?.message);
          mInterstitialAd = null
        }

        override fun onAdLoaded(interstitialAd: InterstitialAd) {
          Log.d(TAG, 'Ad was loaded.');
          mInterstitialAd = interstitialAd
        }
      })
        
    }
}

以及 mIntersitialAd 的使用:

mInterstitialAd.fullScreenContentCallback = object: FullScreenContentCallback() {
  override fun onAdDismissedFullScreenContent() {
    Log.d(TAG, 'Ad was dismissed.');
  }

  override fun onAdFailedToShowFullScreenContent(adError: AdError?) {
    Log.d(TAG, 'Ad failed to show.');
  }

  override fun onAdShowedFullScreenContent() {
    Log.d(TAG, 'Ad showed fullscreen content.');
    mInterstitialAd = null;
  }
}

正如@a_local_nobody 提到的,我们不能,但在这种情况下,我们可以只删除 lateinit,并使其成为 nullable 并使用带有 elvis[ 的实例=17=]

private var mInterstitialAd: InterstitialAd? = null

访问它时只需使用 ?. ,这样你就可以将它设置为 null

mInterstitialAd?.fullScreenContentCallback = //...

似乎是文档中的错误,如果用 lateinit

声明该变量,则无法将其设置为 null
 private lateinit var foo: String?

这也不是有效代码,因为 lateinit 不能用于可为 null 的变量

有关 lateinit 的文档 here

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

The modifier can be used on var properties declared inside the body of a class (not in the primary constructor, and only when the property does not have a custom getter or setter) as well as for top-level properties and local variables. The type of the property or variable must be non-null, and it must not be a primitive type.


对于任何对替代解决方案感兴趣的人,请查看@rajan.kali

提供的答案