Kotlin is a statically-typed programming language for the JVM and the browser, built by a team at JetBrains and designed as a pragmatic and easy-to-use Java alternative. In this presentation we'll explore the most notable Kotlin features, such as:
- Extension functions
- Null-safety
- Smart casts
- and many more
Check out and see that programming in Kotlin is fun!
23. CLASSES
open class Person(val name: String, var age: Int)
// Java
public class Person {
private final String name;
private Integer age;
public Person(String name, Integer age) { // }
public String getName() { // }
public Integer getAge() { // }
public void setAge(Integer age) { // }
}
CONSTRUCTORS
25. CLASSES
data class Person(val name: String, var age: Int)
‣ equals() & hashCode() $0
‣ toString() $0
‣ componentN() functions $0
‣ copy() function $0
‣ TOTAL FREE!
DATA CLASSES
26. CLASSES
val name = person.component1()
val age = person.component2()
COMPONENTN() FUNCTIONS
27. CLASSES
val name = person.component1()
val age = person.component2()
for ((name, age) in people) {
println("$name is $age years old")
}
DESTRUCTURING DECLARATIONS
28. CLASSES
class Person {
companion object {
val FIELD_NAME = "name"
fun isOlderThan(person: Person, age: Int) =
person.age > age
}
}
println(Person.isOlderThan(person, 30))
STATIC -> OBJECT
29. CLASSES
public final class StringUtils {
public static String capitalize(String str) {
// TODO: return capitalized string
return str;
}
}
StringUtils.capitalize(“a”);
UTILS IN JAVA
34. NULL SAFETY
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // OK
val l = a.length
val l = b.length // error: variable 'b' can be null
NULLABLE VS NON-NULL TYPES
35. NULL SAFETY
val l = if (b != null) b.length else -1
CHECKING FOR NULL: SIMPLE APPROACH