// Java code
public class MainActivity extends Activity {
private Button button;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setText("HELLO");
}
}
// Kotlin code
class MainActivity : AppCompatActivity() {
private var button: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button)
button?.text = "HELLO"
}
}
–
// Kotlin code
class MainActivity : AppCompatActivity() {
private lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button)
button.text = "HELLO"
}
}
'lateinit' modifier is allowed only on mutable properties
if (this::button.isInitialized == false) {
// 還沒初始化喔
}
–
// Kotlin code
class MainActivity : AppCompatActivity() {
private val button: Button by lazy {
findViewById(R.id.button)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.text = "HELLO"
}
}
–