Kotlin promises a well-readable and concise syntax, modern language features and functional programming with high security. Does the Java alternative, thanks to its seamless interaction with Android, make the hearts of app developers beat faster?

After five years of development, JetBrains launched the long-awaited version of Kotlin 1.0 in February 2016 and promised stability: Future Kotlin versions are no longer required for existing code. As a statically typed general-purpose language for JVM and browsers, Kotlin can be used wherever Java is running.
The following extended “Hello World” demonstrates a first impression of the concise spelling and at the same time good readability. Even without prior experience the example would be understandable to most Java developers.
import java.util.*
fun main(args: Array) {
val name = if (args.size > 0) args[0] else "Publikum"
val zuschauer = Gast(name, title = Title.wertes)
println(zuschauer)
println("Hallo ${zuschauer.title} $name")
}
data class Gast(val name: String,
var zeit: Date = Date(),
val title: Title?)
enum class Title { Herr, Frau, wertes }
The example shows some properties that make working with Kotlin efficient. This includes the concise keywords and optional semicolons at the end of the line or the use of expressions in string templates. Parameters can have default values and thus become optional.
As a statically and strictly typed language Kotlin offers the well-known good security, but saves the developer unnecessary typing. Thanks to Type Inference, local variables, in particular, open their type themselves, so that type specifications are usually only necessary at interfaces.
The Data class Guest is a simple, extensible value container. Kotlin takes much of the classic boilerplate code, such as getter and setter methods, null value checks, equals (), hashCode (), and toString () implementations, as well as individual convenience functions. Data Classes can be decomposed easily into their individual properties.
var (zname, _, ztitel) = zuschauer
The functionally equivalent Java implementation of the three-line DataClass guest, however, puts it on stately 100 lines.
The fact that the Kotlin code, despite its brevity, is nevertheless well and intuitively readable, becomes clear in practice by the short training period. A lot of basic knowledge and the desire for more elegant code is often enough for experienced Java developers to open up a large part of the Kotlin functions, using compilers and IDEs.
Where intuition no longer suffices, a glance into the successful documentation helps. Kotlin Koans is suitable for the first steps or further study. This curriculum of 42 learning units can be worked out directly in the browser or with the “Kotlin Koans” plug-in in the free IntelliJ IDE (unfortunately not in Android Studio).
Android development with Kotlin
When it comes to Kotlin in the context of the Android development, the language is certainly characterized by its interoperability. Despite the many advanced language features, Kotlin is content with Java 6 bytecode and, unlike Java 8, is unrestrictedly compatible with all Android versions.
In the project, Java and Kotlin libraries as well as individual classes of the source code can be freely mixed in both languages and can access each other without restrictions. By means of a conversion function in Android Studio, developer projects can gradually migrate to Kotlin and thus experience a direct comparison. The seamless access in both directions emphasizes Kotlin clearly from other JVM languages.
From the same house as Kotlin, IntelliJ IDEA also comes from. The IDE forms the basis for Google’s official development environment Android Studio. In addition, Androids builds system Gradle from version 3 on Kotlin as an additional possibility for the build definitions. Both of these promises excellent tooling integration and future-proofing.
The introduction to the app development with Kotlin succeeded very easily. Under File | Settings | Plugins can be installed Kotlin via caps] Install JetBrains plugin [/ caps] in Android Studio. A reboot later the key combination Ctrl + Shift + A offers the action Configure Kotlin in Project under the keyword Kotlin. And developers can already use Kotlin in the project. A more detailed guide can be found in the official step-by-step guide.
Using the Convert Java File to Kotlin File action, individual Java classes can now be automatically transferred to Kotlin. In more complex classes manual rework is occasionally required to a small extent. As a rule, these are due to strict zero-value treatment in Kotlin.
In the type system of Kotlin, zero has a place of honor opposite that of Java: Kotlin types know whether they can contain null values. Compiler and IDE require stringent consideration of the interface contract. For example, TextView always guarantees a value, while ViewGroup? can also have zero values and thus has to be treated specifically in the control flow as well as in the case of deregulation:
var toolbar: ViewGroup? = null
var textView: TextView = TextView(baseContext)
// All statements generate compiler errors
toolbar.measuredHeight
textView = toolbar.getChildAt(0) as TextView
The treatment of zero values sweetened Kotlin with many abbreviations. Under Java the following code would be necessary for the requested checks:
TextView child = null;
if (toolbar != null && toolbar.getChildAt(0) instanceof TextView) {
child = (TextView) toolbar.getChildAt(0);
}
textView = child != null ? child : new TextView(getBaseContext());
if (textView instanceof EditText) {
((EditText) textView).selectAll();
}
val child = toolbar?.getChildAt(0) as? TextView
textView = child ?: TextView(baseContext)
if (textView is EditText) {
textView.selectAll()
}
Access to UI elements
In the context of Android Kotlins Properties bring along some other interesting features. The synthetic properties of the Kotlin Android Extensions offer a true productivity boost. One of the biggest sources of Boilerplate code on Android is likely to be familiar to developers: the continuous recurring pattern for accessing the views in the Activities or Fragments using the findViewById () method.
EditText editTitle = (EditText) v.findViewById(R.id.edit_title);
editTitle.setText(mItem.getTitle());
CheckBox enabledBox = (CheckBox) v.findViewById(R.id.enable_box);
enabledBox.setChecked(true);
Button createButton = (Button) v.findViewById(R.id.create_entry);
createButton.setOnClickListener(new OnClickListener() {
@Override public void onClick(View button) {
createElement();
}
});
import kotlinx.android.synthetic.main.activity_hello.*
// ...
edit_title.setText(mItem.title)
enable_box.isChecked = true
create_entry.setOnClickListener { createElement() }
val lateinit id: String
val imm: InputMethodManager by lazy ( {
getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager } )
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
id = getString(R.string.app_name)
imm.showInputMethodPicker()
}
fun Fragment.toast(msg: String,
dur: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this.getActivity(), msg, dur).show()
}
var EditText.stringValue: String
get() = text.toString()
set(str) { setText(str) }
val Int.dpInPixel: Int get() = (
this * Resources.getSystem().displayMetrics.density + 0.5f
).toInt()
toast("Hallo!")
nameEdit.stringValue = "Unbekannter"
val p = 5.dpInPixel
view.setOnClickListener(new OnClickListener() {
@Override public void onClick(View view) {
view.scrollTo(0,0);
}
});
fun ifNougatOrNewer(f: () -> Unit) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
f()
}
}
It can be used without round brackets thanks to the short-cut notes.
ifNougatOrNewer {
showVRButton()
}
A large part of the Kotlin Standard Library supplements the existing Java classes with extensions by higher-order functions. They often retrofit advanced, but commonly used functions like filter ().
val list = listOf("a", "b", "c", "d")
for (index in list.indices.filter { it % 2 == 0 }) {
println("$index -> ${list[index]}")
}
package com.kalitut.helloworld
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.EditText
import kotlinx.android.synthetic.main.activity_hello.*
import java.util.*
class HelloActivity : AppCompatActivity() {
private val gast = Gast(name = "Publikum")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_hello)
modelToView()
editName.setOnEditorActionListener { v, i, e ->
gast.name = editName.inhalt()
modelToView()
false
}
anredeGroup.setOnCheckedChangeListener({ g, id ->
gast.titel = when (id) {
radioHerr.id -> Titel.Herr
radioFrau.id -> Titel.Frau
else -> Titel.wertes
}
modelToView()
})
}
fun modelToView() {
labelGruss.text = gast.anrede
}
}
enum class Titel { wertes, Herr, Frau, Doktor }
data class Gast(var titel: Titel = Titel.wertes,
var name: String, val geburt: Date? = null) {
val anrede: String
get() = "Hallo $titel $name!"
}
fun EditText.inhalt(): String = text.toString()

Leave a Reply