Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Kotlin Night Pitesti | September 22nd, 2017

44a168e6578c2cc83aaf54a38458ade9?s=47 Magda Miu
September 22, 2017

Kotlin Night Pitesti | September 22nd, 2017

44a168e6578c2cc83aaf54a38458ade9?s=128

Magda Miu

September 22, 2017
Tweet

Transcript

  1. Intro to Kotlin Magda Miu

  2. None
  3. None
  4. What is Kotlin? • Statically typed language • From Jetbrains

    • Inspired by Java, Scala, C#, Groovy etc. • Targets: JVM and Javascript
  5. 1.0 Release 1.1 Release Kotlin is born Gradle Android Official

    Spring Timeline (Kotlin 1.1.4 is out) Chart source: https://github.com/jetbrains/kotlin-workshop
  6. Conventions • The same conventions like on Java • Uppercase

    for types • Lower camelCase for methods and properties • Semicolons are optional • Reverse notation for packages • A file could contain multiple classes • The folder names not have to match the package name
  7. Development tools • JDK • Version 6, 7, 8 and

    9 • Kotlin Compiler • Editor or IDE • IntelliJ IDEA, Android Studio, NetBeans, Eclipse
  8. Build tools • Maven • Gradle • Kobalt • Ant

    • Command Line
  9. None
  10. Basic Data Types Numbers Characters Booleans Arrays Strings Any Nothing

  11. Properties: val and var • val is immutable (read-only) and

    you can only assign a value to them exactly one time. This is the recommended type to use. • var is mutable and can be reassigned. • The type inference is more powerful than Java • Unit in Kotlin corresponds to the void in Java. Unit is a real class (Singleton) with only one instance. • Nothing is a type in Kotlin that represents “a value that never exists”, that means just “no value at all”.
  12. private final int a = 1; private int b =

    2; private final int c = 3; private int d = 4; public int getA() { return a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public int getD() { return d; } public void setD(int d) { this.d = d; } val a: Int = 1 var b: Int = 2 val c = 3 var d = 4 Properties: val and var
  13. String templates • Kotlin supports template expressions • Simple reference

    uses $ • Complex references uses ${} • Raw Strings
  14. class KotlinClass { fun main(args: Array<String>) { val first =

    "Intro to" val second = "Koltin" var both = "$first $second" println("$both has ${both.length}") println(""""$both" has ${both.length}""") } } /* 1. Menu>Tools>Kotlin>Show Kotlin Bytecode 2. Click on the Decompile button 3. See the java code */ String templates Public final class JavaClass { public final void main(@NotNull String[] args) { Intrinsics.checkParameterIsNotNull(args, "args"); String first = "Intro to"; String second = "Koltin"; String both = "" + first + ' ' + second; String var5 = "" + both + " has " + both.length(); System.out.println(var5); var5 = '"' + both + "\" has " + both.length(); System.out.println(var5); } }
  15. Null safety • No more NPEs • Possible causes for

    NPE: • !! • throw NullPointerException(); • External Java code • Data inconsistency with regard to initialization
  16. Null safety • No more NPEs • Possible causes for

    NPE: • !! • throw NullPointerException(); • External Java code • Data inconsistency with regard to initialization class KotlinClass { val notNullString: String = null //error! val nullableString: String? = null //condition checks var theString: String? = "abc" val length1 = if (theString != null) theString.length else -1 //safe calls val length2 = theString?.length //elvis operator val length3 = theString?.length ?: -1 //use !! val length4 = theString!!.length //safe casts val aInt: Int? = theString as? Int }
  17. Class • Many classes in the same file • Classes

    and methods are final by default. Use open for extensibility. • Only properties(public by default) and functions(fun) • No new keyword on instantiation • lateinit for properties (not null) and they should be mutable • init block is equal with the constructor in Java • inner keyword to be able to access members of the surrounding class
  18. class KotlinClass(var name: String) { lateinit var gdg: GDGPitesti val

    language: String init { language = "Kotlin" } fun initializeName (name: String) { gdg = GDGPitesti(name) } inner class GDGPitesti(val text: String) fun sayItFromGDG(): String = "${gdg.text} $name $language" } fun main(args: Array<String>) { var a = KotlinClass("loves") a.initializeName("GDG Pitesti") print(a.sayItFromGDG())//GDG Pitesti loves Kotlin } Class public final class JavaClass { @NotNull public KotlinClass.GDGPitesti gdg; @NotNull private final String language; @NotNull private String name; @NotNull public final KotlinClass.GDGPitesti getGdg() { KotlinClass.GDGPitesti var10000 = this.gdg; if(this.gdg == null) { Intrinsics.throwUninitializedPropertyAccessExcept ion("gdg"); } return var10000; } …
  19. Data Class • data class contains: • properties • equals

    • hashCode • toString • copy • component (Destructuring Declarations)
  20. data class Coordinate(var lat: Double, var lon: Double) fun main(args:

    Array<String>) { val city1 = Coordinate(24.5, 48.5) //copy val city2 = city1.copy(lat = 25.7) //component val (theLat, theLon) = city2 println(city1) println(city2) println(theLat) println(theLon) } Data Class public final class CoordinateJava { private double lat; private double lon; public final double getLat() { return this.lat; } public final void setLat(double var1) { this.lat = var1; } public final double getLon() { return this.lon; } public final void setLon(double var1) { this.lon = var1; } ….
  21. Interface • Could contain abstract methods and/or properties • They

    need to be initialized in the implementing class in order to respect the contract of the interface • override keyword is mandatory • A property declared in an interface can either be abstract, or it can provide implementations for accessors.
  22. interface GDG { val name: String fun getCity(): String }

    class GDGPitesti: GDG{ override val name: String = "GDG" override fun getCity(): String = "$name Pitesti" } fun main(args: Array<String>) { println(GDGPitesti().getCity()) } Interface
  23. Object • The object keyword creates singleton in Kotlin •

    An object declaration inside a class can be marked with the companion keyword • Members of the companion object can be called by using simply the class name as the qualifier (like static on Java) • The name of the companion object can be omitted, in which case the name Companion will be used
  24. object SingletonClass { fun getHello(): String = "Hello Singleton" }

    class CompaniedClass(val str: String) { companion object Printer { fun getHello(): String = "Hello Companion" } } class NoNameCompaniedClass(val str: String) { companion object { fun getHello(): String = "Hello No Name Companion" } } fun main(args: Array<String>) { SingletonClass.getHello() // Hello Singleton CompaniedClass.getHello() // Hello Companion NoNameCompaniedClass.getHello() // Hello No Name Companion } Object
  25. fun main(args: Array<String>) { val a = 4; val b

    = 7 val max = if (a > b) { println("$a is grater than $b"); a } else { println("$b is grater than $a"); b } println(max) println(describe("GDG")) for (i in 1..10 step 2) { print("$i ") }} fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Awesome" } It’s all about expressions...
  26. Collections and Lambdas • Kotlin distinguishes between mutable and immutable

    collections • The supported operations on Collections are: map, flatMap, forEach, fold, reduce, filter, zip etc. • to is in infix function fun main(args: Array<String>) { listOf(1, 2, 3); mutableListOf("a", "b", "c") setOf(1, 2, 3); mutableSetOf("a", "b", "c") mapOf(1 to "a", 2 to "b", 3 to "c") mutableMapOf("a" to 1, "b" to 2, "c" to 3) val aList = listOf(1, 2, 4) println(aList.map { elem -> elem + 1 }) println(aList) println(aList.filter { it != 1 }) fun sum(a: Int, b: Int) = a + b println(aList.reduce(::sum)) }
  27. Extensions functions • Add operators to the classes by using

    the operator • Create infix functions with the infix keyword • Extension functions are normal static methods bearing no connection with the class they are extending, other than taking an instance of this class as a parameters fun main(args: Array<String>) { val x = "Kotlin" println(x.last()) val m1 = Matrix(1, 2, 3, 4) val m2 = Matrix(1, 1, 1, 1) val m3 = m1 + m2 println("${m3.a} ${m3.b} ${m3.c} ${m3.d}") } fun String.last(): Char { return this[length - 1] } class Matrix(val a: Int, val b: Int, val c: Int, val d: Int) { operator fun plus(matrix: Matrix): Matrix { return Matrix(a + matrix.a, b + matrix.b, c + matrix.c, d + matrix.d) } }
  28. Questions?

  29. Resources • Images source: buzzfeed.com • http://jussi.hallila.com/Kollections/ • https://try.kotlinlang.org •

    https://kotlinlang.org/docs/books.html