This is my very first post on Kotlin for Android language.
What is Kotlin?
Kotlin is a language by JetBrains, the company behind IntelliJ IDEA, which Android Studio is based on, and other developer tools. Kotlin is purposely built for large scale software projects to improve upon Java with a focus on readability, correctness, and developer productivity.
The language was created in response to limitations in Java which were hindering development of JetBrains' software products and after an evaluation of all other JVM languages proved unsuitable. Since the goal of Kotlin was for use in improving their products, it focuses very strongly on interop with Java code and the Java standard library.
Why Kotlin?
- 100% interoperable with Java - Kotlin and Java can co-exist in one project. You can continue to use existing libraries in Java.
- Concise - Drastically reduce the amount of boilerplate code you need to write.
- Safe - Avoid entire classes of errors such as null pointer exceptions.
- It's functional - Kotlin uses many concepts from functional programming, such as lambda expressions.
Syntax Crash Course
Defining packages
Package specification should be at the top of the source file:
package my.demo
import java.util.*
// ...
Variables
Defining local variables
Assign-once (read-only) local variable:
val a: Int = 1
val b = 1 // `Int` type is inferred
val c: Int // Type required when no initializer is provided
c = 1 // definite assignment
Mutable variable:
var x = 5 // `Int` type is inferred
x += 1
Functions
Function having two Int parameters with Int return type:
fun sum(a: Int, b: Int) :Int {
return a + b
}
Function with an expression body and inferred return type:
fun sum(a: Int, b: Int) = a + b
Function returning no meaningful value:
fun printSum(a: Int, b: Int): Unit {
print(a + b)
}
Unit return type can be omitted:
fun printSum(a: Int, b: Int) {
print(a + b)
}
Using collections
Iterating over a collection:
for (name in names)
println(name)
Checking if a collection contains an object using in operator:
if (text in names) // names.contains(text) is called
print("Yes")
Using lambda expressions to filter and map collections:
names
.filter { it.startsWith("A") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { print(it) }
Null Safety
val x: String? = "Hi"
x.length // Won't compile
val y: String = null // Won't compile
Dealing with null
// using the safe call operator ?.
x?.length // This returns x.length if x is not null, and null otherwise
// Elvis Operator ?:
val len = x?.length ?: -1 // This will return -1 if x is null
No comments:
Post a Comment