Wednesday, 15 May 2019

Assignment should be lifted out of 'try' in Kotlin for Android

I have decided to build my next Android application using a modern programming language called Kotlin instead of the traditional Java language. So far, I enjoy the ideas of mutability control using var and val keywords, and nullability control using question mark (?) keyword.

There is one other interesting feature of Kotlin that I figured out myself while writing a standard try-catch block of code in Java manner. My Android studio IDE shows this suggestion for my block of code: Assignment should be lifted out of 'try'.

I read further about the issue and realise that in Kotlin you can write the whole try-catch block of code in just one line of code. The following line of code is from the Kotlin official page for handling exceptions.

val a: Int? = try { parseInt(input) } catch (e: NumberFormatException) { null }

Overall, Kotlin seems to be a good replacement for Java and would enhance the readability and save coding time in the long run. I will update in my blog if I find some other interesting feature of the Kotlin language.

1 comment:

  1. A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. 澳洲代写