I'm trying to define a variable globally which is of the class WebView. In Android Java it could be easy done by writing the it
Java for global variable
< ClassName > < variableName >
But in Kotlin I'm facing issue with its declaration.
class MainActivity : AppCompatActivity() {
var mywebview : WebView //<- This shows Property must be initialized or be abstract
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onStart() {
super.onStart()
mywebview = findViewById(R.id.webViewGyrix) as WebView
mywebview.setWebViewClient(object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
view?.loadUrl(url);
return true
}
} )
mywebview.loadUrl("http://www.example.com/")
}
You can use late initialization - you don't have to make WebView nullable
lateinit var webView: WebView
This shows Property must be initialized or be abstract
Then initialize it i.e. to null
. This is not a final value and you will be able to change it later:
var mywebview : WebView? = null
Alternatively, you can use lateinit feature of Kotlin, which would let you prevent having nullable mywebview
if not needed:
lateinit var webView: WebView
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With