Safer Code
Write safer code and avoid NullPointerExceptions in your app.
var output: String
output = null // Compilation error
==================================
val name: String? = null // Nullable type
println(name.length()) // Compilation error
Readable and Concise
Focus on expressing your ideas and wirte less boilerplate code.
// Create a POJO with getters, setters, equals(), hashCode(), toString(), and copy() with a single line:
data class User(val name: String, val email: String)
Lambdas
Use lambdas to simplify your code.
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
doSomething();
}
});
button.setOnClickListener { doSomething() }
Default and named arguements
Reduce the number of overloaded functions by using default arguments.
Call functions using named arguments to make your code more readable.
fun format(str: String,
normalizeCase: Boolean = true,
upperCaseFirstLetter: Boolean = true,
divideByCamelHumps: Boolean = false,
wordSeparator: Char = ' ') {
…
}
==================================
// Call function with named arguments.
format(str, normalizeCase = true, upperCaseFirstLetter = true)
Say Goodbye to findViewById
Avoid findViewById() calls in your code. Focus on writing on your logic with less verbosity.
import kotlinx.android.synthetic.main.content_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// No need to call findViewById(R.id.textView) as TextView
textView.text = "Kotlin for Android rocks!"
}
}
Extend functionality without inheritance
Extension functions and properties let you easily extends functionality of classes without inheriting from them. calling code is readable and natural.
// Extend ViewGroup class with inflate function
fun ViewGroup.inflate(layoutRes: Int): View {
return LayoutInflater.from(context).inflate(layoutRes, this, false)
}
==================================
// Call inflate directly on the ViewGroup instance
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = parent.inflate(R.layout.view_item)
return ViewHolder(v)
}
100% Interoperable with Java
Add as tittle or as much of Kotlin as you want. Kotlin is a JVM language that's completely interoperable with Java.
// Calling Java code from Kotlin
class KotlinClass {
fun kotlinDoSomething() {
val javaClass = JavaClass()
javaClass.javaDoSomething()
println(JavaClass().prop)
}
}
==================================
// Calling Kotlin code from Java
public class JavaClass {
public String getProp() { return "Hello"; }
public void javaDoSomething() {
new KotlinClass().kotlinDoSomething();
}
}
Building and Publishing the Kotlin application for android