32

A quick and fast intro to Kotlin

Embed Size (px)

Citation preview

Page 1: A quick and fast intro to Kotlin
Page 2: A quick and fast intro to Kotlin

KOTLIN

● Primary target JVM● Javascript● Compiled in Java byte code● Created for industry

Core goals is 100% Java interoperability.

Page 3: A quick and fast intro to Kotlin

KOTLIN main features

ConciseDrastically reduce the amount of

boilerplate code you need to write.

SafeAvoid entire classes of errors such

as null pointer exceptions.

InteroperableLeverage existing frameworks and

libraries of the JVM with 100% Java

Interoperability.

Page 4: A quick and fast intro to Kotlin

data class Person(var name: String, var surname: String, var age: Int)

Create a POJO with:

● Getters● Setters● equals()● hashCode()● toString()● copy()

Concise

public class Person {

final String firstName;

final String lastName;

public Person(...) {

...

}

// Getters

...

// Hashcode / equals

...

// Tostring

...

// Egh...

}

Page 5: A quick and fast intro to Kotlin

KOTLIN lambdas

● must always appear between curly brackets● if there is a single parameter then it can be referred to by it

Concise

val list = (0..49).toList()val filtered = list

.filter({ x -> x % 2 == 0 })

val list = (0..49).toList()val filtered = list

.filter { it % 2 == 0 }

Page 6: A quick and fast intro to Kotlin

NULL safety

// ERROR

// OK

Page 7: A quick and fast intro to Kotlin

// OK

// ERROR

NULL safety

Page 8: A quick and fast intro to Kotlin

// ERROR

NULL safety

Page 9: A quick and fast intro to Kotlin

// ERROR

SAFE CALL

NULL safety

Page 10: A quick and fast intro to Kotlin

Extend existing classes functionality

Ability to extend a class with new functionality without having to inherit from the class

● does not modify classes● are resolved statically

Page 11: A quick and fast intro to Kotlin

Extend existing classes functionality

fun String.lastChar() = this.charAt(this.length() - 1)

// this can be omitted

fun String.lastChar() = charAt(length() - 1)

fun use(){

Val c: Char = "abc".lastChar()

}

Page 12: A quick and fast intro to Kotlin

Everything is an expression

val max = if (a > b) a else b

val hasPrefix = when(x) {

is String -> x.startsWith("prefix")

else -> false

}

when(x) {

in 1..10 -> ...

102 -> ...

else -> ...

}

boolean hasPrefix;

if (x instanceof String)

hasPrefix = x.startsWith("prefix");

else

hasPrefix = false;

switch (month) {

case 1: ... break

case 7: ... break

default: ...

}

Page 13: A quick and fast intro to Kotlin

Default Parameters

fun foo( i :Int, s: String = "", b: Boolean = true) {}

fun usage(){

foo( 1, b = false)

}

Page 14: A quick and fast intro to Kotlin

for loop

can iterate over any type that provides an iterator implementing next() and hasNext()

for (item in collection)

print(item)

for ((index, value) in array.withIndex()) {

println("the element at $index is $value")

}

Page 15: A quick and fast intro to Kotlin

Collections

● Made easy● distinguishes between immutable and mutable collections

val numbers: MutableList = mutableListOf(1, 2, 3)

val readOnlyNumbers: List = numbers

numbers.add(4)

println(readOnlyView) // prints "[1, 2, 3, 4]"

readOnlyNumbers.clear() // -> does not compile

Page 16: A quick and fast intro to Kotlin

Java 6

Page 17: A quick and fast intro to Kotlin

// Using R.layout.activity_main from the main source setimport kotlinx.android.synthetic.main.activity_main.*

class MyActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)

textView.setText("Hello, world!") }}

public class MyActivity extends Activity() { @override

void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

TextView textView = (TextView) findViewById(R.id.textView); textView.setText("Hello, world!"); }}

Kotlin Android Extensions

Page 18: A quick and fast intro to Kotlin

Extension functions

fun Fragment.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {

Toast.makeText(getActivity(), message, duration).show()

}

fragment.toast("Hello world!")

Page 19: A quick and fast intro to Kotlin

Activities

startActivity( intentFor< NewActivity > ("Answer" to 42) )

Intent intent = new Intent(this, NewActivity.class);intent.putExtra("Answer", 42);startActivity(intent);

Page 20: A quick and fast intro to Kotlin

Functional support (Lambdas)

view.setOnClickListener { toast("Hello world!") }

View view = (View) findViewById(R.id.view);view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {

Toast.makeText(this, "asdf", Toast.LENGTH_LONG).show();

}});

Page 21: A quick and fast intro to Kotlin

Dynamic Layout

scrollView { linearLayout(LinearLayout.VERTICAL) { val label = textView("?")

button("Click me!") { label.setText("Clicked!")}

editText("Edit me!")

// codice koltin// ...

}}.style(...)

?

Click me!

Edit me!

Page 22: A quick and fast intro to Kotlin

Easily mixed with Java

● Do not have to convert everything at once● You can convert little portions● Write kotlin code over the existing Java code

Everything still works

Page 23: A quick and fast intro to Kotlin

Kotlin costs nothing to adopt

● It’s open source● There’s a high quality, one-click Java to Kotlin converter tool● Can use all existing Java frameworks and libraries● It integrates with Maven, Gradle and other build systems.● Great for Android, compiles for java 6 byte code● Very small runtime library 924 KB

Page 24: A quick and fast intro to Kotlin

Kotlin usefull links

● A very well done documentation : Tutorial, Videos● Kotlin Koans online● Constantly updating in Github, kotlin-projects● Talks: Kotlin in Action, Kotlin on Android

Page 25: A quick and fast intro to Kotlin

What Java has that Kotlin does not

https://kotlinlang.org/docs/reference/comparison-to-java.html

Page 26: A quick and fast intro to Kotlin

Primitive Types

Everything is an objectwe can call member functions and properties on any variable.

What Java has that Kotlin does not

val a: Int? = 1 val b: Long? = a

print(a == b)

Page 27: A quick and fast intro to Kotlin

Primitive Types

Everything is an objectwe can call member functions and properties on any variable.

What Java has that Kotlin does not

val a: Int? = 1 val b: Long? = a

print(a == b) // FALSE //

Page 28: A quick and fast intro to Kotlin

Primitive Types

Everything is an objectwe can call member functions and properties on any variable.

What Java has that Kotlin does not

val b: Byte = 1

val i: Int = b

val i: Int = b.toInt()

val a: Int? = 1 val b: Long? = a

print(a == b) // FALSE //

Page 29: A quick and fast intro to Kotlin

Primitive Types

Everything is an objectwe can call member functions and properties on any variable.

What Java has that Kotlin does not

val b: Byte = 1

val i: Int = b // ERROR //

val i: Int = b.toInt() // OK //

val a: Int? = 1 val b: Long? = a

print(a == b) // FALSE //

Page 30: A quick and fast intro to Kotlin

Static Members

class MyClass {

companion object Factory {

fun create(): MyClass = MyClass()

}

}

val instance = MyClass.create()

What Java has that Kotlin does not

Singleton

object MyClass {

// ....

}

Page 31: A quick and fast intro to Kotlin

Gradle Goes Kotlin

https://kotlinlang.org/docs/reference/using-gradle.html

Page 32: A quick and fast intro to Kotlin

Thank You

Erinda Jaupaj@ErindaJaupi