How much code is this on Kotlin? Just this simple data class:
class UserEntity { var userId: String? = null var name: String? = null var email: String? = null var mobileNumber: String? = null }
Null safety
When we develop the application using Java, most of our code is defensive. We need to keep checking continuously if something is null before we use it. Otherwise we may find unexpected NullPointerException. Kotlin, as many other languages, is null safe because we need to explicitly specify if an object can be null by using the safe call operator.
We can do things like this:
var a: String = “abc” a = null // compilation errorvar b: String? = “abc” b = null // ok
Checking for null in conditions:
if (b != null && b.length > 0) { print(“String of length ${b.length}”) } else { print(“Empty string”) }
Safe Calls with Kotlin
b?.length
Extension functions
We can add new functions to any class. It´s a much more readable substitute to the typical utility classes we all have in our projects. We could, for instance, add a new method to fragments to show a toast:
fun Fragment.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(getActivity(), message, duration).show() }
We can do things like this with Kotlin:
fragment.toast(“Hello world!”)
Functional support (Lambdas)
What if instead of having to write the creation of a new listener every time we need to declare what a click should do, we could just define what we want to do? We can indeed. This (and many more interesting things) is what we get thanks to lambda usage:
view.setOnClickListener { toast(“Hello world!”) }
As a part of our exploration about how Kotlin actually works with the real world application, below are the Kotlin specimen codes we have created for our Hello World News application. The objective is to fetch data from server to mobile device and getting it displayed to UI in the desired format using Kotlin. The specimen codes are described in three different stages:
- Code for fetching the list of data to mobile device from server
- Code for displaying that data to User Interface
- Code for data rendering using Recycler Adapter
Fetching the list of data to mobile device from server
// Get the list of data from server private fun getNewsList() { //Create retrofit Service var mNewsService: NewsService = ApiProduction(this).provideService(NewsService::class.java) //List of source: https://newsapi.org/sources //List of sort by option: https://newsapi.org/#apiArticles var apiCall: Observable<NewsListResponse> = mNewsService.getNewsApi(“techcrunch”, “top”, getString(R.string.new_api_key) //Test API Key ) RxAPICallHelper().call(apiCall, object : RxAPICallback<NewsListResponse> { override fun onSuccess(newsItems: NewsListResponse) { //status= “error” in case of error if (newsItems.getStatus().equals(“ok”)) { setNewsData(newsItems) } } override fun onFailed(throwable: Throwable) { } }) }
Displaying that data to User Interface
// Update data on UI private fun setNewsData(newsItems: NewsListResponse) { recyclerNews.layoutManager = LinearLayoutManager(this) val newsRecyclerAdapter: NewsRecyclerAdapter = NewsRecyclerAdapter() newsRecyclerAdapter.setData(newsItems.getArticles() as ArrayList<NewsListResponse.Article>) recyclerNews.adapter = newsRecyclerAdapter newsRecyclerAdapter.setOnItemClick(object : NewsRecyclerAdapter.MyAdapterListener { override fun onItemViewClick(mUrl:String,position: Int) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse( mUrl))) } }) }