Skip to content

Instantly share code, notes, and snippets.

@choongyouqi
Last active April 27, 2018 07:42
Show Gist options
  • Save choongyouqi/f09132681c7a55c2b52ca6e72bc211d4 to your computer and use it in GitHub Desktop.
Save choongyouqi/f09132681c7a55c2b52ca6e72bc211d4 to your computer and use it in GitHub Desktop.
[Kotlin] Kotlin in a nutshell #cheatsheet
import java.util.*
fun main(args: Array<String>) {
var numList = 1..10
for (x in numList.step(2)) println("x: $x");
var nullableString: String? = "Hello";
nullableString = null;
println("nullableString: $nullableString")
//var length = nullableString!!.length;
var length = nullableString?.length;
println("length: $length")
var longString: String? = """Use Triple Double-Quotes
|to type in multiple lines
|third line.
""".trimMargin();
println("typeOf: ${longString}");
println("arithmetic: ${1 + 2}");
val aToZString: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
println("aToZString: ${aToZString.substring(2..4)}");
println("aToZString: ${aToZString.subSequence(2, 4)}");
println("aToZString: ${aToZString.contains("PQR")}");
//Array
var myArray = arrayOf(1, 1.23, "Doug");
println(myArray);
println(myArray[1]);
myArray[1] = 3.142;
println("size: ${myArray.size}");
println("First: ${myArray.first()}");
println("IndexOf(3.142): ${myArray.indexOf(3.142)}");
//Collections
var sqArray = Array(5, { x -> x * x });
var intArray: Array<Int> = arrayOf(1, 2, 4);
//Ranges (26min)
val alpha = "A".."Z";
println("alpha: ${"R" in alpha}");
val oneTo10 = 1..10;
val tenTo1 = 10.downTo(1);
val twoTo20 = 2.rangeTo(20);
val rng3 = oneTo10.step(3);
for (x in rng3) println("rng3: $x ")
for (x in tenTo1.reversed()) println("Reversed: $x ")
//Conditional Operator (When)
val age = 1;
when (age) {
0, 1, 2, 3, 4 -> println("Go to Preschool")
5 -> println("Go to Kindergarten")
in 6..17 -> {
val grade = age - 5
println("Go to Grade $grade")
}
else -> println("Go to college")
}
//Looping
for (x in 1..10) {
println("Loop: $x");
}
val rand = Random();
val MagicNum = rand.nextInt(50) + 1;
var arr3: Array<Int> = arrayOf(3, 6, 9);
for (i in arr3.indices) {
println("Mult 3: $i")
}
for ((index, value) in arr3.withIndex()) {
println("Index: $index, Value: $value");
}
//Functions
fun add(num1: Int, num2: Int): Int = num1 + num2
println("5 + 4 = ${add(5, 4)}");
fun subtract(num1: Int, num2: Int): Int = num1 - num2
println("5 - 4 = ${subtract(5, 4)}");
println("4 - 5 = ${subtract(num2 = 5, num1 = 4)}");
fun sayHello(name: String): Unit = println("Hello $name");
sayHello("Paul")
val (two, three) = nextTwo(1);
println("1 $two $three");
println("Sum: ${getSum(1, 2, 3, 4, 5)}")
val multiply = { num1: Int, num2: Int -> num1 * num2 }
println("5 * 3 = ${multiply(5, 3)}")
println("5! = ${fact(5)}")
//Filter (51min)
var numList2 = 1..20
val evenList = numList2.filter { it % 2 == 0 }
evenList.forEach { n -> println(n) };
//Make Function
val multiply3 = makeMathFun(3);
println("5 * 3 = ${multiply3(5)}")
val numList3 = arrayOf(1, 2, 3, 4, 5);
val myCustomFunc = { num1: Int -> num1 * 2 };
mathOnList(numList3, myCustomFunc)
//Collection Operators
val numList4 = 1..20
val listSum = numList4.reduce { x, y -> x + y }
println("Reduce Sum: $listSum")
val listSum2 = numList4.fold(5) { x, y -> x + y }
println("Reduce Sum: $listSum2")
val times7 = numList2.map { it * 7 }
times7.forEach { n -> println("*7: $n") }
//Exception
val divisor = 0;
try {
if (divisor == 0) {
throw IllegalArgumentException("Can't take divide by Zero")
} else {
println("5 / $divisor = ${5 / divisor}")
}
} catch (e: IllegalArgumentException) {
println("${e.message}");
}
//Multable/Immutable List
var list1: MutableList<Int> = mutableListOf(1, 2, 3, 4, 5);
var list2: List<Int> = listOf(1, 2, 3);
list1.add(6)
println("1st: ${list1.first()}");
println("Last: ${list1.last()}");
println("2nd: ${list1[1]}");
var list3 = list1.subList(0, 3)
list1.remove(2);
list1.removeAt(2);
list1.forEach { n -> println("Multable List: $n") }
//Map (1 HOUR 8 MIN Mark)
val map = mutableMapOf<Int, Any?>()
val map2 = mutableMapOf(1 to "Doug", 2 to 25)
map[1] = "Derek"
map[2] = 42
println("Map Size: ${map.size}")
map.put(3, "Pittsburg")
map.remove(2)
for ((x, y) in map) {
println("Key: $x Value: $y")
}
//Classses
val bowser = Animal("Bowser", 20.0, 13.5)
bowser.getInfo()
val spot = Dog("Spot", 20.0, 13.5, "You Qi")
spot.getInfo()
val tweety = Bird("Tweety", true)
tweety.fly(10.0);
//Null Values
var nulVal: String? = null
fun returnNull(): String? {
return null
}
fun returnNull2(): String? = null
var nullVal2 = returnNull();
if (nullVal2 != null) {
println("nullVal2.length")
}
//var nullVal3 = nullVal2!!.length
var nullVal4: String = returnNull() ?: "No Name";
println("nullVal4: $nullVal4")
}
fun nextTwo(num: Int): Pair<Int, Int> {
return Pair(num + 1, num + 2);
}
fun getSum(vararg nums: Int): Int {
var sum = 0;
nums.forEach { n -> sum += n }
return sum;
}
fun fact(x: Int): Int {
tailrec fun factTail(y: Int, z: Int): Int {
if (y == 0) return z
else return factTail(y - 1, y * z)
}
return factTail(x, 1);
}
fun makeMathFun(num1: Int): (Int) -> Int = { num2 -> num1 * num2 }
fun mathOnList(numList: Array<Int>, myFunc: (num1: Int) -> Int) {
numList.forEach {
println("it: $it: ${myFunc(it)}")
}
}
open class Animal(val name: String,
var height: Double,
var weight: Double) {
init {
val regex = Regex(".*\\d+.*")
require(!name.matches(regex)) { "Animal name can't contain number" }
require(height > 0) { "Height must be greater than 0" }
require(weight > 0) { "Weight must be greater than 0" }
}
open fun getInfo(): Unit {
println("$name is $height tall and weighs $weight")
}
}
class Dog(name: String,
height: Double,
weight: Double,
var owner: String) : Animal(name, height, weight) {
override fun getInfo() {
println("$name is $height tall and weighs $weight and is owned by $owner")
}
}
interface Flyable {
var flies: Boolean
fun fly(distMiles: Double): Unit
}
class Bird constructor(val name: String, override var flies: Boolean = true) : Flyable {
override fun fly(distMiles: Double) {
if (flies) {
println("$name flies $distMiles miles")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment