Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

KOTLIN KILLED

JAVA STARS
KOTLIN
EVERYTHING IS
AN OBJECT
val i: Int = 7
val d: Double = i.toDouble()
val c: Char = 'c'
val i: Int = c.toInt()
PROPERTIES
public class Person {

private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

...

Person person = new Person();


person.setName("name");
String name = person.getName();
class Person {

var name: String = ""

...

val person = Person()


person.name = "name"
val name = person.name
class Person {

var name: String = ""

get() = field.toUpperCase()

set(value) {
field = "Name: $value"
}

}
;
SEMICOLONS ARE NOT
NECESSARY
VAL VS VAR
MUTABLE (VAR)
Person person = new Person();

person = new Person();


var person = Person();

person = Person();
IMMUTABLE (VAL)
val s = "Example" // A String

val i = 23 // An Int
VAL
AS MUCH AS POSSIBLE
CLASSES
class MainActivity {

}
class Person(name: String, surname: String) {
init {
... // Default logic in the constructor
}
}
open class Animal(name: String)
class Person(firstName: String, lastName: String) : Animal(firstName)
FUNCTIONS
fun onCreate(savedInstanceState: Bundle?) {
}
THE BILLION-DOLLAR MISTAKE
NULL-SAFETY
Forecast forecast = null;

forecast.toString();
QUESTION MARKS TO IDENTIFY NULLABLE TYPES
val a: Int? = null
val a: Int? = null
a.toLong()
val a: Int? = null
...
if (a != null) {
a.toLong()
}
SAFE CALL OPERATOR (?.)
val a: Int? = null
...
a?.toLong()
ELVIS OPERATOR (?:)
val a: Int? = null
...
val myLong = a?.toLong() ?: 0L
val myLong = a?.toLong() ?: return false

val myLong = a?.toLong() ?: throw IllegalStateException()


val a: Int? = null
a!!.toLong()
LAMBDAS
public interface OnClickListener {
void onClick(View v);
}
fun setOnClickListener(listener: (View) -> Unit)
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Click", Toast.LENGTH_SHORT).show();
}
});
view.setOnClickListener(object : OnClickListener {
override fun onClick(v: View) {
toast("Click")
}
})
view.setOnClickListener({ view -> toast("Click")})
view.setOnClickListener({ toast("Click") })
view.setOnClickListener() { toast("Click") }
view.setOnClickListener { toast("Click") }
DATA CLASSES
data class Forecast(val date: Date, val temperature: Float, val details: String)
AVAILABLE METHOD
• equals(): it compares the properties from both objects to ensure they
are
identical.
• hashCode(): we get a hash code for free, also calculated from the
values of the
properties.
• copy(): you can copy an object, modifying the properties you need.
val f1 = Forecast(Date(), 27.5f, "Shiny day")
val f2 = f1.copy(temperature = 30f)
REFERENCE
http://try.kotlinlang.org/
http://kotlinlang.org/docs
THANKS
Twitter: @mbonifazi
Email:
matteobonifazi[@]gmail.com - matteo.bonifazi[@]codemotion.it

You might also like