Concepts for Kotlin
Kotlin is a modern, statically typed programming language developed by JetBrains in 2011. It is designed to be fully interoperable with Java, making it an excellent choice for Android development, as well as for backend and frontend applications. Kotlin is known for its concise syntax, which reduces boilerplate code and improves readability. It offers features such as null safety, extension functions, coroutines for asynchronous programming, and type inference, enhancing developer productivity and code safety. Kotlin's seamless integration with existing Java codebases, along with its strong tooling support and active community, has contributed to its rapid adoption in a wide range of software development projects.
Print Text
fun main() { println("Hello World!"); }Comments
// one line comment /* multi line comment */
Variables
val carCount = 2; val name: String = "Joe"; val isPurple: Boolean = true;
Data Types
val carCount: Int = 2; val age: Byte = 15; val seaLevel: Short = -10000; val usBudget: Long = 11000000000L; val lightSpeed: Long = 11799312874L; val myGPA: Float = 3.45F; val piValue: Double = 3.14159265; val lastLetter: Char = 'Z'; val isMale: Boolean = true; val myName: String = "Joe";
Math Op
val carCount = 6; val truckCount = 3; val total = carCount + truckCount; println(total); val subtract = carCount - truckCount; println(subtract); val multiple = carCount * truckCount; println(multiple); val divisible = carCount / truckCount; println(divisible); // performs division and gets remainder which is 0 val modulo = carCount % truckCount; println(modulo);
Math Functions
import kotlin.math.*; import kotlin.random.Random; val power = Math.pow(3.0, 6.0); println(power ); val root = Math.sqrt(16.0); println(root ); val floorVal = Math.floor(3.14); println(floorVal ); val ceilVal = Math.ceil(4.3); println(ceilVal ); val roundVal = Math.round(3.4); println(roundVal ); // random number from 0 to 100 val random = Random val ranNum = random.nextInt(0, 101) println(ranNum)
If/Else
val carCount = 6; if (carCount > 3) { println("More than three cars"); } else if (carCount == 3) { println("Equal to three cars"); } else { println("Less than three cars"); }Ternary
val carCount = 3; val result = if (carCount > 2) "Yes" else "No"; println(result);
Switch
val carCount = 3; when (carCount) { 1 -> print("One car"); 2 -> print("Two cars"); 3 -> print("Three cars"); else -> { print("More than three"); } }Functions
fun handleCars(cars: Int, wheels: Int): Int { val total: Int = cars * wheels; return total; } val result: Int = handleCars(3, 4); println(result);Interpolation
val name = "Joe"; val car = "Mazda"; val result = "${name} drives a ${car}" println(result);Type Casting
import kotlin.math.* fun squareA (length: Int): String { val result: Double = length.toDouble().pow(2); return result.toString(); } val squareL: String = "4"; val convertedVal: Int = squareL.toInt(); val area: String = squareA(convertedVal); println(area);Date and Time
// kotlin can use java packages import java.time.Year; import java.time.LocalDate; import java.time.format.DateTimeFormatter import java.util.Date; // global UTC date val date = Date() println("${date}\n"); // time in milliiseconds val millitime = System.currentTimeMillis(); println("${millitime} \n") // current year val currentYear = Year.now().getValue(); println("${currentYear}\n"); // local date val localDate = LocalDate.now(); println(localDate); val formatted = DateTimeFormatter.ofPattern("MM-dd-yyyy"); // reformatted date with month first val formattedDate = localDate.format(formatted); println(formattedDate);Classes
class Cars { val carList = mutableListOf<String>(); fun addCar(name: String) { carList.add(name); } fun removeFirst() { carList.removeAt(0); } fun getFirstVal():String { if(carList.count() > 0) { return carList[0]; } return ""; } } val newList = Cars(); newList.addCar("Honda"); newList.addCar("Mazda"); newList.addCar("Toyota"); newList.removeFirst(); val firstCar = newList.getFirstVal(); println(firstCar);Inheritance
open class User( Username:String, Password:String ) { var username:String = Username var password:String = Password open fun fetchUsername():String { return username } } class Admin( username:String, password:String, Id:String ): User( username, password ) { var id:String = Id fun getAdminID():String { return id } } val user = Admin("alpha0", "pw1", "1FE") println(user.fetchUsername()) println(user.getAdminID())Method Overload
class UserForm { val formA:String = "alpha"; val formB:String = "beta"; val formC:String = "gamma"; val formD:String = "epsilon"; fun getForm(age:Int):String { if (age > 65) { return formA; } return formB; } fun getForm(id:String):String { if (id == "1FE") { return formA; } return formC; } fun getForm( isMilitary:Boolean, isNasa:Boolean ):String { if (isMilitary || isNasa) { return formD; } return formA; } } val form =UserForm(); val myAge = 67; val myId = "1FE"; val veteran = false; val nasa = true; val form1 = form.getForm(myAge); val form2 = form.getForm(myId); val form3 = form.getForm(veteran, nasa); println(form1 ); println(form2 ); println(form3 );Abstract Class
abstract class Animation { abstract fun walk(); abstract fun run(); abstract fun idle(); } class Human: Animation() { override fun walk() { println("Human walks" ); } override fun run() { println("Human runs" ); } override fun idle() { println("Human idles" ); } } class Zombie: Animation() { override fun walk() { println("Zombie walks" ); } override fun run() { println("Zombie runs" ); } override fun idle() { println("Zombie idles" ); } } val player = Human(); player.walk(); val boss1 = Zombie(); boss1.run();Static Class
class Helper { companion object { fun CircleA(radius:Double):Double { val power = radius.pow(2.0); return 3.14 * power; } fun SquareA(length:Double):Double { return length.pow(2.0); } } } // convert type to match function val circleR = 3; val circle = Helper.CircleA(circleR.toDouble()); println(circle); val squareR = 3; val square = Helper.SquareA(squareR.toDouble()); println(square);Arrays/Lists
var names = mutableListOf("Joe", "Alex", "Bob"); names.set(1, "Tom"); val name = names.get(1); val numItems = names.size; println(name); println(numItems);Array Methods
val cars = mutableListOf<String>("Honda", "Mazda", "Toyota"); // number of elements println(cars.count()) // print value at index 1 println(cars[1]) // last index number println("${cars.lastIndex}\n") // removes element at index 1 cars.removeAt(1); println(cars[1]); // clears entire list cars.clear(); println("${cars}\n"); // checks if list empty println(cars.isEmpty());Concatenation
val carsListKr = arrayOf("Kia", "Hyundai", "Daewoo"); val carsListJp = arrayOf("Honda", "Mazda", "Toyota"); val combined = carsListKr.plus(carsListJp); println(combined[1]); println(combined[4]);Sort Method
var ages = mutableListOf<Int>(5, 3, 1, 6, 7, 4, 19); ages.sort(); println(ages);
Objects
val user = object { val first = "Joe"; val last = "Doe"; val age = 23; val retired = false; val carBrands = arrayOf("Mazda", "Toyota"); fun fullName (): String { return "${first} ${last}" } } println(user.first); println(user.carBrands[1]); println(user.fullName());Maps (Key/Value)
var carMap : HashMap<String, String> = HashMap<String, String> (); carMap.put("Joe", "Toyota"); carMap.put("Bob", "Mazda"); carMap.put("Tom", "Ford"); println(carMap["Tom"]) carMap.remove("Tom"); println(carMap.containsKey("Tom"));Sets
val cars = hashSetOf<String>(); cars.add("Mazda"); cars.add("Toyota"); cars.add("Honda"); println(cars.contains("Honda")); cars.remove("Honda"); println(cars.contains("Honda"));Stack
import java.util.ArrayDeque; val cars = ArrayDeque<String>(); cars.push("Mazda"); cars.push("Toyota"); cars.push("Honda"); println(cars.peek()); cars.pop(); println(cars.peek());Queues
import java.util.Queue; import java.util.LinkedList; val cars: Queue<String> = LinkedList<String>(); cars.add("Mazda"); cars.add("Toyota"); cars.add("Honda"); println(cars.peek()); cars.remove(); println(cars.peek());Linked List
class Node(Value: String) { var value = Value; var next:Node? = null; } class LinkedList { var head:Node ? = null; fun addValue(newVal:String) { var newNode = Node(newVal); if (head == null) { head = newNode; } else { var current = head; while(current?.next != null) { current = current.next; } current?.next = newNode; } } fun returnHead():String? { return head?.value; } fun traverse() { var current = this.head; while(current != null) { println(current.value); current = current.next; } } } val carList = LinkedList(); carList.addValue("Mazda"); carList.addValue("Toyota"); carList.addValue("Honda"); println(carList.returnHead()); carList.traverse();Graphs
import java.util.Queue; import java.util.LinkedList; import java.util.ArrayDeque; class Graph { val graphMap = HashMap<String, MutableList<String>> (); fun addNode(newVal:String) { val tempArr = mutableListOf<String>(); graphMap.put(newVal, tempArr); } fun addVertices( node1:String, node2:String ) { val tempArr = mutableListOf<String>(); if(graphMap.containsKey(node1) == false) { graphMap.put(node1, tempArr); } if(graphMap.containsKey(node2) == false) { graphMap.put(node2, tempArr); } graphMap[node1]?.add(node2); graphMap[node2]?.add(node1); } fun breadthTraverse(start:String) { val queue: Queue<String> = LinkedList<String>(); queue.add(start); val visited = HashMap<String, Boolean>(); visited.put(start, true); while(queue.count() > 0) { var currentVal = queue.peek(); println(currentVal); queue.remove(); val tempArr = graphMap[currentVal]; for (item in tempArr.orEmpty()) { if( visited.containsKey(item) == false ) { queue.add(item); visited.put(item, true); } } } } fun depthTraverse(start:String) { val stack = ArrayDeque<String>(); stack.push(start); val visited = HashMap<String, Boolean>(); visited.put(start, true); while(stack.count() > 0) { val currentVal = stack.peek(); println(currentVal); stack.pop(); val tempArr = graphMap[currentVal]; for (item in tempArr.orEmpty()) { if( visited.containsKey(item) == false ) { stack.add(item); visited.put(item, true); } } } } } val newGraph = Graph(); newGraph.addNode("a"); newGraph.addVertices("a", "b"); newGraph.addVertices("a", "c"); newGraph.addVertices("b", "d"); newGraph.addVertices("b", "e"); newGraph.addVertices("d", "f"); newGraph.addVertices("d", "g"); newGraph.addVertices("d", "h"); newGraph.addVertices("e", "i"); newGraph.addVertices("e", "j"); newGraph.breadthTraverse("a"); newGraph.depthTraverse("a");For Loops
val names = mutableListOf("Joe", "Alex", "Bob"); for (name in names.orEmpty()) { println(name); }While Loops
val cars = mutableListOf<String>("Mazda", "Toyota", "Honda"); while(cars.count() > 0) { println("${cars[0]}\n"); cars.removeAt(0); } println(cars.count())Loop Breaks
val cars = mutableListOf<String>("Toyota", "Honda", "Mazda"); for ((index, car) in cars.withIndex()) { if (car == "Honda") { println("Found at index ${index}"); break; } println("Visted index ${index}"); }Recursion
fun getSum(arr:MutableList<Int>):Int { if(arr.count() == 0) return 0; var firstVal = arr[0]; arr.removeAt(0); return firstVal + getSum(arr); } var testArr = mutableListOf<Int>(1, 2, 4, 5); val sum = getSum(testArr); println(sum);Regex Words
val pattern = Regex("\\w+"); val phrase = "I am legend"; val match = pattern.find(phrase); println(match?.value);Regex Numbers
val pattern = Regex("\\d+"); val phrase = "I am 23"; val match = pattern.find(phrase); println(match?.value);Regex Test
val pattern = "Lee".toRegex(); val phrase = "Bob Lee"; val result = pattern.containsMatchIn(phrase); println(result);
Regex Characters
val pattern = Regex("#+\\w+"); val phrase = "##I am legend##"; val match = pattern.find(phrase); println(match?.value);