Created
May 30, 2018 04:24
-
-
Save ivalexandru/250fa6c5b2f799d6550814a4abf9d3b7 to your computer and use it in GitHub Desktop.
Kotlin_Null_Safety.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package academy.learnprogramming.calculator | |
import android.support.v7.app.AppCompatActivity | |
import android.os.Bundle | |
import android.widget.EditText | |
import android.widget.TextView | |
class MainActivity : AppCompatActivity() { | |
//varianta1 | |
//we tell kotlin that we're using a non-nullable variable, but that we'll delay giving it a value until later | |
private lateinit var result:EditText | |
private lateinit var newNumber: EditText | |
//varianta2 | |
//when using by lazy, you're defining a function that will be called to asign a value to the property; the function will be called the first time the property is accessed, then the value is CACHED, so that the function isn't called again. | |
//as long as we don't access displayOperation untill onCreate is called, this will work fine | |
//avantajul e ca displayOperation poate fi declarat VAL, spre deosebire de lateinit care vrea doar VAR | |
private val displayOperation by lazy {findViewById<TextView>(R.id.operation) } | |
//the lazy function is thread-safe; if the displayOperation property is accessed by 2-3 threads simultaneously, the function will still only be called once | |
//versiune modificata, because our activity class can't be accessed by more than one thread, so it's no need for the extra overhead that lazy includes by default (for multi-threads) | |
//aka vom adauga inca un parametru to disable the tread-safe code, whenever we're using it IN AN ACTIVITY. | |
private val displayOperation by lazy(LazyThreadSafetyMode.NONE) {findViewById<TextView>(R.id.operation) } | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment