Home Development for Android 16 Kotlin development tips for android. Part 3

16 Kotlin development tips for android. Part 3

by admin

And hello again, on the eve of the launch of the The basic Android development course. , we share the final part of the article "16 Kotlin Development Tips for Android."
16 Kotlin development tips for android. Part 3

Read the first part
Read part two


One of the leading features of Kotlin is its commitment to zero security. The lateinitstatement provides a simple way to provide zero security and initialize a variable the way Android requires. This feature is great, however, it takes some getting used to after working in Java. One idea is that the field is immediately declared with the possibility of being null :

var total = 0var toolbar:Toolbar? = null

This language function can cause difficulties when working with Android layouts, because we don’t know how to declare representations before the layout is declared, because it’s not clear where they will exist, in Activity or Fragment This is compensated by additional checks for the possibility of a null value in each place we interact with, but this is a pain in the ass. That’s why it’s better to use the modifier lateinit :

lateinit var toolbar: Toolbar

Now you, as the developer, should not refer to Toolbar until it is actually initialized. This works fine when used together with a library, e.g. Butter Knife :

@BindView(R.id.toolbar) lateinit var toolbar: Toolbaroverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)ButterKnife.bind(this)// now you can access the toolbar without any problemstoolbar.setTitle("Hello There")}

Security of types

Some Android conventions require secure typing because normal typing does not exclude code errors. For example, the typical way to create a fragment in an action involves checking through the FragmentManager to rule out that it already exists. Only if it doesn’t, will you create it and add it to the action. When you first look at typing in Kotlin, you can implement this as follows :

var feedFragment: FeedFragment? = supportFragmentManager.findFragmentByTag(TAG_FEED_FRAGMENT) as FeedFragmentBut this could cause a failure. The as statement will get an object with a null value, which in this case is excluded.The correct version is :var feedFragment: FeedFragment? = supportFragmentManager.findFragmentByTag(TAG_FEED_FRAGMENT) as? FeedFragmentif (feedFragment == null) {feedFragment = FeedFragment.newInstance()supportFragmentManager.beginTransaction().replace(R.id.root_fragment, feedFragment, TAG_FEED_FRAGMENT).commit()}


Leveraging let allows you to execute a block if the value of the object is not zero. This allows you to avoid null checks and makes the code more readable. In Java, it looks like this :

if (currentUser != null) {text.setText(currentUser.name)}And in Kotlin it looks like this :user?.let {println(it.name)}

This code is much easier to read plus it automatically creates a variable with a non-zero value without the danger of zeroing it.


We have to check the fields many times throughout the development of an Android app. If you have managed this without using Kotlin, you probably know about the TextUtils class in Android. The TextUtils class looks like this :

if (TextUtils.isEmpty(name)) {// here we inform the user}

In this example you can notice that the user can set even just spaces as the username and it will pass the check. isNullOrEmpty and isNullOrBlank built into the Kotlin language, eliminate the need for TextUtils.isEmpty ( someString ) and provide the added benefit of checking only spaces. You can use something like :

// If we don't care about the spaces in the name...if (number.isNullOrEmpty()) {// ask user to enter a name}//if spaces are critical...if (name.isNullOrBlank()) {//tasking the user to enter a name}

Field validation is often encountered when you need to register in an application. These built-in methods are great for checking a field and alerting the user if something is wrong. For more complex checks, you can use extension methods, such as for email addresses :

fun TextInputLayout.isValidForEmail(): Boolean {val input = editText?.text.toString()if (input.isNullOrBlank()) {error = resources.getString(R.string.required)return false}else if (emailPattern.matcher(input).matches()) {error = resources.getString(R.string.invalid_email)return false}else {error = nullreturn true}}

Tips for the advanced

Did you know you can use lambda expressions to create cleaner, more concise code?
For example, when working in Java, it is typical to have a simple listener class such as :

public interface OnClickListener {void onClick(View v);}

A distinctive feature of Kotlin is that it performs SAM (Single Abstract Method) conversions for Java classes. The click listener in Java, which looks like :

textView.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {// doing something}});In Kotlin, it can be abbreviated to :textView.setOnClickListener { view ->// doing something}

Oddly enough, this conversion is not possible for SAM interfaces created in Kotlin. This may surprise and even frustrate new Kotlin users a bit. If the same interface is defined in Kotlin, the listener looks like this :

view.setOnClickListener(object : OnClickListener {override fun onClick(v: View?) {//doing something}})

To reduce such code, you can write your listeners into the class as follows :

private var onClickListener: ((View) -> Unit)? = nullfun setOnClickListener(listener: (view: View) -> Unit) {OnClickListener = listener}// we will contact them lateronClickListener?.invoke(this)

This takes you back to a simple lambda syntax that makes automatic SAM conversion possible.


I’ve compiled the most useful tips from everything I’ve learned since I started getting interested in the Kotlin language. Hopefully, knowing these tips will help you significantly in developing your own projects.
That’s all for now. See you at course !

You may also like