Why the lines are crossed out and the error where the dot is I don't understand
package com.ggenius.whattowearkotlin.data.network
import android.content.Context
import android.net.ConnectivityManager
import com.ggenius.whattowearkotlin.internal.NoConnectivityException
import okhttp3.Interceptor
import okhttp3.Response
class ConnectivityInterceptorImpl(
context: Context?
) : ConnectivityInterceptor {
private val appContext = context.applicationContext
override fun intercept(chain: Interceptor.Chain): Response {
if (!isOnline())
throw NoConnectivityException()
return chain.proceed(chain.request())
}
private fun isOnline() : Boolean {
val connectivityManager = appContext.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager
val networkInfo = connectivityManager.activeNetworkInfo
return networkInfo != null && networkInfo.isConnected
}
}
Why the error where the dot is I don't understand?
The context.applicationContext is showing error because your context is nullable. Whenever you define your variable with Type followed by ? is nullable in Kotlin.
As you passing context: Context?, so context is nullable. To access nullable objects properties or methods you need to use objectName followed by ?. This prevents the NullPointerException that makes Kotlin null safe.
In you example you need to do;
private val appContext = context?.applicationContext
// Note that appContext will also be nullable.

