https://developer.android.com/kotlin/common-patterns
This topic focuses on some of the most useful aspects of the Kotlin language when developing for Android.
The following sections use Fragment examples to highlight some of Kotlin's best features.
You can declare a class in Kotlin with the class keyword. In the following example, LoginFragment is a subclass of Fragment. You can indicate inheritance by using the : operator between the subclass and its parent:
class LoginFragment : Fragment()
In this class declaration, LoginFragment is responsible for calling the constructor of its superclass, Fragment.
Within LoginFragment, you can override a number of lifecycle callbacks to respond to state changes in your Fragment. To override a function, use the override keyword, as shown in the following example:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.login_fragment, container, false)}
To reference a function in the parent class, use the super keyword, as shown in the following example:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)}
In the previous examples, some of the parameters in the overridden methods have types suffixed with a question mark ?. This indicates that the arguments passed for these parameters can be null. Be sure to handle their nullability safely.
In Kotlin, you must initialize an object's properties when declaring the object. This implies that when you obtain an instance of a class, you can immediately reference any of its accessible properties. The View objects in a Fragment, however, aren’t ready to be inflated until calling Fragment#onCreateView, so you need a way to defer property initialization for a View.
The lateinit lets you defer property initialization. When using lateinit, you should initialize your property as soon as possible.
The following example demonstrates using lateinit to assign View objects in onViewCreated:
class LoginFragment : Fragment() {
private lateinit var usernameEditText: EditText
private lateinit var passwordEditText: EditText
private lateinit var loginButton: Button
private lateinit var statusTextView: TextView
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
usernameEditText = view.findViewById(R.id.username_edit_text)
passwordEditText = view.findViewById(R.id.password_edit_text)
loginButton = view.findViewById(R.id.login_button)
statusTextView = view.findViewById(R.id.status_text_view)
}
...}