name: portada class: portada-slide, center, middle # Kotlin ## Per programadors <%= teacher_slides_start %> --- # Hello World ``` /* * Prints a welcome message */ fun main() { // Code to be executed println("Hello, World!") } ``` --- # Notes - fun main() és una funció executable - No calen punts i comes al final de la linia - El tabulat es opcional però recomanat - A diferencia de Java/C# accepta mètodes fora de classes - println imprimeix per consola --- # Constants i variables ``` val nom = "Alba" val cognom : String = "Chang" val edat = 34 val alturaMetres : Double = 1.64 ``` ``` var x = 4 x = 5 ``` --- # Constants i variables - Notes - Si el tipus es pot inferir no cal posar-lo - Nota: intenta no utilitzar var fun main() { val catCount = 4 val dogCount = 5 val animalCount = catCount + dogCount println(animalCount) } --- # Tipus bàsics - Int - Long - Double - Float - Boolean - String - Char --- # Conversions de tipus ``` val string = 3.toString() val integer = "4".toInt() val long = 232.toLong() val double = 15478487894L.toDouble() ``` --- # Terminal I/O ``` println("whats your name?") val name = readln() println("How old are you?") val name = readln().toInt() ``` --- # Funcions ```kotlin /** * Calculates area from given dimensions */ fun rectangleArea(length: Double, width: Double): Double { return length * width } fun main() { val area = rectangleArea(4.5, 2.5) val area2 = readRectangle(length=4.5, width=2.5) } ``` --- # Funcions Per funcions d'una sola linia podem usar ```kotlin fun rectangleArea(length: Double, width: Double) = length * width ``` --- # Valors per defecte ``` fun rectangleArea(length: Double = 0, width: Double = 0) = length * width rectangleArea(4.5, 2.1) rectangleArea(4.5) rectangleArea() rectangleArea(length = 2.5) rectangleArea(width = 2.5) ``` --- # Class ```kotlin class Rectangle(val width: Double, val height: Double) fun main() { val rectangle = Rectangle(1.5, 3.5) println(rectangle.width) println(rectangle.height) } ``` --- # Class methods ```kotlin class Rectangle(val width: Double, val height: Double){ val area get() = width * height fun multiplyWithBy(mutiplier: Double) = width*mutiplier } fun main() { val rectangle = Rectangle(1.5, 3.5) println(rectangle.area) println(rectangle.multiplyWithBy(2.3)) } ``` --- # Data Class methods ```kotlin data class Rectangle(val width: Double, val height: Double){} fun main() { val rectangle = Rectangle(1.5, 3.5) println(rectangle) val rectangle2 = rectangle.copy(height = 4.8) } ``` --- # Comparar - == compara segons el mètode equals ```kotlin println(5==5) //true println("abcd"=="abcd") // true println(listOf(2,3)==listOf(2,3)) // true data class Rectangle(val width: Double, val height: Double) println(Rectangle(2.1,3.2)==Rectangle(2.1, 3.2)) // true ``` --- # Ifs ```kotlin if(condition){ println("yes") } ``` ```kotlin if(condition){ println("yes") } else { println("false") } ``` ```kotlin if(condition) println("yes") else println("false") ``` --- # If/else retornen resultat ```kotlin val text = if(condition) "yes" else "no" ``` ```kotlin val text = if(condition) "yes" else "no" ``` --- # When ```kotlin val value: Int = readln().toInt() when (value) { 0 -> println("zero") 1 -> println("one") 2, 3, 4 -> println("many") else -> println("too many") } ``` --- # When ```kotlin val value: Int = scanner.nextInt() val text = when (value) { 0 -> "zero" 1 -> "one" 2, 3, 4 -> "many" else -> "too many" } ``` --- # When When com a if/else encadenats ``` when { x % 2 != 0 -> print("x is odd") y % 2 == 0 -> print("y is even") else -> print("x+y is odd") } ``` --- # Estructures iteratíves ## Repeat ``` repeat(3) { println(it) } ``` --- # Estructures iteratíves ## For ``` for (nom_variable in range) { // codi a executar } ``` ``` // print 1 2 3 for (i in 1..3) { println(i) } ``` --- # For - Ranges ``` for (i in 1..4) print(i) for (i in 4 downTo 1) print(i) for (i in 1..8 step 2) print(i) for (i in 8 downTo 1 step 2) print(i) for (i in 1 until 10) { // i in [1, 10), 10 is excluded print(i) } ``` --- # Estructures iteratíves ## While ``` while(condition){ // S'executa mentre la condició és true } ``` --- # Break Surt del bucle actual ``` while(condition){ if(condition2) break } ``` --- # Continue Torna a l'inici del bucle ``` while(condition){ if(condition2) continue } ``` --- # Return Retorna el resultat d'una funció, però també surt de tots els bucles. ``` while(condition){ if(condition2) return } ``` --- # Llistes ``` val stringList : List
= listOf("one", "two", "one") val numberList : List
= listOf(5, 9, 55) val rectangleList : List
= listOf(Rectangle(1.5,2.7), Rectangle(3.1, 5.4)) ``` - Són llistes de tipus read-only --- # Llistes ``` List(size){ codi_per_cada_element } ``` - Dins del codi, el valor __it__ representa la posició actual - List és un mètode constructor per això s'escriu amb majúscules --- # Llista - inicialització ## Valors calculats ``` // [5, 5, 5, 5] val fives = List(4) { 5 } // [0, 1, 2, 3] val zeroToThree = List(4) { it } // [0, 2, 4, 6] val doubled = List(4) { it * 2 } val fromInput = List(4) {scanner.readLine()?.toInt() ?: 5} val myList = List(n){ it } ``` --- # Llistes ``` val value = values[5]; val size = values.size val alphabet = listOf('a', 'b', 'c', 'd') println(alphabet.first()) // 'a' println(alphabet.last()) // 'd' println(alphabet.lastIndex) // 3 ``` --- # Recorre llistes ```kotlin for(i in 0..list.lastIndex){ print(list[i]) } ``` ```kotlin for(value in values){ print(value) } ``` ```kotlin values.forEach { print(it) } ``` ```kotlin values.forEach { value -> print(value) } ``` --- # Recorregut de llistes ## For each indexed ```kotlin for((i, value) in values.withIndex()){ print("$i - $value") } ``` ```kotlin val values = listOf(5,10,50) values.forEachIndexed{ i, value -> print("$i - $value") } ``` --- # Mètodes i operacions de List ``` val fruits = listOf("apple", "pear", "banana") val vegetables = listOf("cucumber", "pepper", "broccoli") val shoppingList = fruits + vegetables val listText = shoppingList.joinToString(", ") //apple, pear, banana, cucumber, pepper, broccoli val listText2 = shoppingList.joinToString(", ", "{", "}") //{apple, pear, banana, cucumber, pepper, broccoli} println(fruits==vegetables) //false - compara la mida i el contingut shoppingList.reversed() ``` --- # Llistes mutables ```kotlin val list : MutableList
= mutableListOf(1, 2, 3,4) val list : MutableList
= mutableListOf
() //buida MutableList(size){ codi_per_cada_element } ``` --- # Llistes mutables ```kotlin val list = mutableListOf
() //[] list.add(1) //[1] afegeix al final list.addAll(listOf(2, 3)) //[1, 2, 3] list += 4 // [1, 2, 3, 4] list += listOf(5, 6) //[1, 2, 3, 4, 5, 6] val index = 0 list.add(index, 10) //[10, 1, 2, 3, 4, 5, 6] afegeix a la posició indicada ``` --- # Llistes mutables ```kotlin val fruits = mutableListOf("Apple", "Banana", "Grape", "Mango") fruits.remove("Apple") //Banana, Grape, Mango fruits.removeAt(0) //Grape, Mango fruits.clear() // {} ``` --- # Matrius ``` val matrix = listOf( listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33) ) val value = matrix[0][0]; println(matrix) //[[11, 12, 13], [21, 22, 23], [31, 32, 33]] ``` --- # Matrius ``` val matrix3x3 = List(3){ List(3){ scanner.nextInt() } } ``` --- # Mètodes de String ``` "abcdefg".substring(1..3) // bcd "abcdefg".replace("c", "X") // abXdefg "abcdefg".first() // a "abcdefg".last() // g "abcdefg".toUpperCase() // ABCDEFG "ABCDEFG".toUpperCase() // abcdefg " abc ".trim() // abc "abcdefg".startsWith("ab") // true "abcdefg".endsWith("fg") // true "a,b,c".split(",") // ["a", "b", "c"] "100€".padStart(10, '.') // ......100€ ```