0% found this document useful (0 votes)
682 views

Kotlin Cheat Sheet: Short Long Sunday Monday Tuesday Wednesday Thursday Friday Saturday

This document provides a cheat sheet on various Kotlin concepts like declaring constants and variables, null safety, strings, enums, functions and more. It includes examples of using constants, variables, type aliases, null checks, safe calls, elvis operator, string interpolation, ranges, tuples, and more Kotlin features.

Uploaded by

yasser fahmaoui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
682 views

Kotlin Cheat Sheet: Short Long Sunday Monday Tuesday Wednesday Thursday Friday Saturday

This document provides a cheat sheet on various Kotlin concepts like declaring constants and variables, null safety, strings, enums, functions and more. It includes examples of using constants, variables, type aliases, null checks, safe calls, elvis operator, string interpolation, ranges, tuples, and more Kotlin features.

Uploaded by

yasser fahmaoui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Kotlin Cheat Sheet

val short:String, val long:String)


Declaring Constants Elvis Operator - ?: {
// const can only be used in top insurance_no = null Sunday ("Sun","SUNDAY"),
level or objects Monday ("Mon","MONDAY"),
const val PI = 3.14 val length = Tuesday ("Tue","TUESDAY"),
insurance_no?.length ?: -1 Wednesday ("Wed","WEDNESDAY"),
// otherwise, use val for constant // length is -1 Thursday ("Thu","THURSDAY"),
val URL = Friday ("Fri","FRIDAY"),
"calendar.learn2develop.net" var gender:String? = null Saturday ("Sat","SATURDAY"),
var genderOfCustomer = }
gender ?: "male" // male
Declaring Variables var colorOfBag:BagColor
val num = 5 // type inference gender = "female" colorOfBag = BagColor.Red
val num2:Int = 6 // explicit type genderOfCustomer =
val msg = "Welcome!" gender ?: "male" // female var colorStr:String =
val name:String colorOfBag.toString()

Casting // colorStr is now "Red"
Type Alias val num1 = 5 // Int val color = colorOfBag.v
typealias CustomerIDType = Int val num2 = 1.6 // Double // color is 3
typealias CustomerNameType = String val num3 = 3.4F // Float
val num4 = num1.toFloat() // 5.0 colorOfBag =
var customerID: CustomerIDType val num5 = num2.toInt() // 1 BagColor.valueOf("Yellow")
var customerName: CustomerNameType val str = num3.toString() // "3.4" // colorOfBag is now BagColor.Yellow
val num6 = str.toInt() // exception
customerID = 12345 var day:DayOfWeek
customerName = "Samanta Choo"
Using let with Null day
val
= DayOfWeek.Friday
s1 = day.long // "FRIDAY"
fun getProductCode(code:String)
Tuples (Pair/Triple) :String? { val s2 = day.short // "Fri"
var pt = Pair(7,8) val code =
if (code=="Diet Coke") "12345" day = DayOfWeek.valueOf("Saturday")
var flight =
else null // day is now DayOfWeek.Saturday
Triple(7031, "ATL", "ORD")
return code
var (flightno, orig, dest) = flight } Characters
// String
print(flightno) //---7031--- val code =
var euroStr = "€"
print(orig) //---ATL--- (getProductCode("Diet Coke"))
print(dest) //---ORD--- code?.let {
// Character
print(code)
var euro:Char = '€'
print(flight.first) //---7031--- } ?:run {
print(flight.second) //---ATL--- print("Code not found")
// €2500
print(flight.third) //---ORD--- }
var price = euro + "2500"
// price is now a String
Nulls Strings
var insurance_no:String? = var
var
str1 = "A string"
str2:String = "A string"
Range Operators
"12345678" // Closed Range Operator
insurance_no = null var str3 = str1 + str2
// prints 5 to 9 inclusive
var str4 = "A" + " " + "String"
for (num in 5..9 step 1) {

Checking for Null print(num)
if (insurance_no != null) { String Interpolation }
val length = insurance_no.length var firstName = "Wei-Meng"
//---prints 9 to 5 inclusive---
} var lastName:String = "Lee"
for (num in 9 downTo 5 step 1) {
var fullName = print(num)
Safe Call Operator - ? "$firstName $lastName" }
insurance_no = null // "Wei-Meng Lee"
val length = insurance_no?.length //---Half-Open Range Operator
// length is null var s = //---prints 5 to 8---
"Value of \$firstName is $firstName" for (num in 5 until 9 step 1) {
val fruits:List<String?> = // "Value of $firstName is Wei-Meng" print(num)
listOf("apple", "orange", null) }

for (fruit in fruits) { Unicode Functions
fruit?.let { val hand = '\u270B'
fun addNums(num1:Int,
print(fruit) val star = '\u2b50'
num2:Int,
}
num3:Int):Int {
}
Enumerations return num1+num2+num3
enum class BagColor(val v:Int) { }
Non-null Assertion Black(1),
val sum = addNums(5,6,7)
Operator - !! White(2),
Red(3),
var insurance_no:String? = Green(4),
"12345678" Yellow(5),
val length = insurance_no!!.length }
// length is 8
enum class DayOfWeek(


Rev 1.3.1 © Wei-Meng Lee , Developer Learning Solutions, http://calendar.learn2develop.net All rights reserved.
var column:Int
Returning Tuple //---numbers3 has now 10 elements )
fun countNumbers(string:String): // all 0s var stone1 = Go(12,16)
Pair<Int,Int>{ var numbers3 = IntArray(10) with(stone1) {
var odd = 3 // same as int[] in Java row = 9
var even = 4 column = 13
// do something //---numbers3 has now 10 elements }
return Pair(odd, even) // from 0 to 9
} numbers3 =
intArrayOf(0,1,2,3,4,5,6,7,8,9) Looping
val count = countNumbers("12345") // prints 0 to 4
// numbers4 has now 10 elements var count = 0
while (count < 5) {
Default Parameter Value // {0,1,4,9,16,25,...}
val numbers4 = IntArray(10) { print (count)
fun join(firstName:String, n -> n*n count += 1
lastName:String, } }
joiner:String=" "):String {
return $firstName$joiner$lastName" // prints 0 to 4
} The it Keyword count = 0
// same as numbers4 repeat (5) {
var fullName = val numbers5 = IntArray(10) { print(count)
join("Wei-Meng", "Lee", ",") it*it count += 1
// Wei-Meng,Lee // "it" is the implicit }
// name of the single parameter
fullName = join("Wei-Meng", "Lee") } // prints 0 to 4
// Wei-Meng Lee for (i in 0..4) {
print(i)
Dictionaries
Variable Arguments val platforms1 = hashMapOf(
}
fun average(vararg nums:Int):Float { "Apple" to "iOS",
var sum: Float = 0F "Google" to "Android", Classes
for (num in nums) { "Microsoft" to "Windows Phone" class MyLocation {
sum += num.toFloat() ) }
}
return sum/nums.size val p1 = platforms1["Apple"] // type inference
} //---"iOS"--- val loc1 = MyLocation()

var avg = average(1,2,3,4,5,6) val p2 = platforms1["Samsung"] // declare and initialize
// 3.5 //---null--- val loc2:MyLocation = MyLocation()

Arrays and Lists val count = platforms1.size


val companies = platforms1.keys Late Initialization
var names = Array<String>(5) {""} val oses = platforms1.values // late initialization (only applies
// 5 elements all containing "" // to var)
platforms1["Samsung"] = "Bada" lateinit var loc3:MyLocation
var OSes: Array<String> = ...
arrayOf("iOS", loc3 = MyLocation()
"Android",
"Windows Phone") val months:HashMap<Int, String> =
hashMapOf()
months[1] = "Jan"
Lazy Initialization
var os1 = OSes[0] // "iOS" // lazy only applies to val
var os2 = OSes[1] // "Android" months[2] = "Feb" public class Example{
var os3 = OSes[2] // "Windows Phone" // defer initialization of an
var count = OSes.size // 3 The when Statement // object until the point at
// which it is needed.
// Array is mutable (Switch) val name: String by lazy {
OSes[2] = "Fuchsia" var grade: Char = 'B' "Johnson"
when (grade) { }
var items: List<Int> = 'A', 'B', 'C', 'D' -> }
listOf(1,2,3,4,5) print("Passed")
var item1 = items[0] // 1 'F' -> val e = Example()
var item2 = items[1] // 2 print("Failed") val name = e.name // "johnson"
var item3 = items[2] // 3 else ->

// error }
print("Undefined") Properties
// items[3] = 9 // list is immutable class MyLocation {
// all properties must be
// mutable (dynamic) Matching Range // initialized
var wishes: MutableList<String> = var percentage: Int = 85 // var for read/write properties
mutableListOf() when (percentage) { var lat:Double? = null
wishes.add("iPhone") in 0..20 -> var lng:Double? = null
wishes.add("iPad") print("Group 1")
in 21..40 -> // val for read-only properties
val arrived:Boolean = false
Array<Int> vs IntArray print("Group 2")
in 41..60 -> }
// declare; numbers0 is now null print("Group 3")
val numbers0: Array<Int> in 61..80 -> val loc = MyLocation()
// same as Integer[] in Java print("Group 4") loc.lat = 57.474392
in 81..100 -> loc.lng = 37.228008
// declare and init; numbers1 now print("Group 5") print(loc.arrived)
// has 10 elements else ->
var numbers1: Array<Int> =
arrayOf(0,1,2,3,4,5,6,7,8,9) }
print("Invalid percentage") Primary Constructor
// primary constructor
// same as numbers1 class MyLocation (var lat:Double,
var numbers2= Data Class var lng:Double) {
arrayOf(0,1,2,3,4,5,6,7,8,9) data class Go ( val arrived:Boolean = false
var row:Int,


Rev 1.3.1 © Wei-Meng Lee , Developer Learning Solutions, http://calendar.learn2develop.net All rights reserved.
fun someMethod() {
val latitude = this.lat var loc5 = MyLocation() Lambda Functions
val longitude = this.lng loc5.lat = 157.474392 // exception //---Button view---
} loc5.lng = 37.228008 val btnOpen =
} print(loc5.arrived) findViewById<Button>(R.id.btnOpen)

var loc = MyLocation(57.474392, // traditional way


37.228008) btnOpen.setOnClickListener(object:
class Distance {
View.OnClickListener{
var miles = 0.0
override fun onClick(v: View?) {
Primary Constructor with var km: Double
set (km) {
...
}}
Initializer Block miles = km / 1.60934
)
class MyLocation (var lat:Double, }
// alternative 1
var lng:Double) { get() {
btnOpen.setOnClickListener(
val arrived:Boolean = false return 1.60934 * miles
{ view ->
} ...
init { } })
this.lat = lat // alternative 2
this.lng = lng var d = Distance() btnOpen.setOnClickListener()
// you can add more code here d.miles = 10.0 { view ->
} print(d.km) // 16.0934 ...
}
fun someMethod() {
val latitude = this.lat
Class Inheritance // alternative 3
btnOpen.setOnClickListener {
val longitude = this.lng // use open to allow the class to be
view ->
} // inherited
...
} open class BaseClass(arg1:String) {
}
// class has a primary
// alternative 4
// constructor with 1 argument
Secondary Constructor }
btnOpen.setOnClickListener {
...
class MyLocation { }
var lat:Double // initializing the parent class via
var lng:Double // the class header
var arrived:Boolean = false class SubClass1(
arg1:String, var numbers =
// secondary constructor arg2:String):BaseClass(arg1) { arrayOf(5,2,8,7,9,4,3,1)
constructor(lat:Double, }
lng:Double) { // return all even numbers
this.lat = lat // initializing the parent class via val evenNumbers = numbers.filter {
this.lng = lng // the secondary constructor using n -> n % 2 == 0
// you can add code here // the super keyword }
} class SubClass2:BaseClass {
constructor(arg1:String, // sum up all the numbers
// secondary constructor; chaining arg2:String): val sums = numbers.reduce {
constructor(lat:Double, super(arg1) { sum, n -> sum + n
lng:Double, } }
arrived:Boolean):
this(lat,lng) { // constructor chaining // convert the list to strings,
this.arrived = arrived constructor(arg1:String): prefix each item with "$"
} this(arg1, "") { val prices = numbers.map{
} } n -> "\$$n"
} }
var loc = MyLocation(57.474392,
// apply GST to items above 3,
37.228008)
// convert the list to strings,
var loc2 = MyLocation(57.474392, open class Shape(length:Float,
37.228008, true) // prefix with "$"
width:Float) {
val pricesWithGST = numbers.map{
var length:Float
n -> "$" + if (n>3) (n*1.07) else n
Custom Getter and Setter var width:Float
}
// a.k.a. computed properties init {
class MyLocation () { // sort in ascending order
this.length = length
var lat:Double = 0.0 val sortedASCNumbers =
this.width = width
set(value) { numbers.sortedBy {
}
if (value > 90 || it
fun perimeter():Float {
value < -90) { }
return 2 * (length + width)
throw }
IllegalArgumentException( // sort in descending order
fun area(): Float {
"Invalid latitude") val sortedDESCNumbers =
return length * width
} numbers.sortedBy {
}
field = value it
}
} }.reversed()
var lng:Double = 0.0 open class Rectangle(length:Float,
set(value) {
if (value > 180 ||
width:Float): Accepting Lambda
Shape(length,width) {
value < -180) { private val INCH_TO_CM = 2.54F Functions as Arguments
throw init { fun bubbleSort(
IllegalArgumentException( this.length = length * items:IntArray,
"Invalid longitude") INCH_TO_CM compareFun:(Int, Int) -> Boolean)
} this.width = width * INCH_TO_CM :IntArray {
field = value }
} } for (j in 0..items.size-2) {
val arrived:Boolean var swapped = false
get() { class Square(length:Float): for (i in 0..items.size-2-j) {
return (this.lat in 57.0..58.0 Rectangle(length, length) { // you need to swap if the
&& this.lng in 37.0..38.0) } // numbers are not in order
} if (!compareFun(items[i],
}
3


Rev 1.3.1 © Wei-Meng Lee , Developer Learning Solutions, http://calendar.learn2develop.net All rights reserved.
items[i+1])) { {
val temp = items[i+1] Instance Methods return (2 * Math.PI *
items[i+1] = items[i] class Car { radius).toFloat()
items[i] = temp var speed = 0 }
swapped = true fun accelerate() { }
} }
} fun decelerate() { var c = Circle(6F)
if (!swapped) break } area = c.area() // 28.274334
} fun stop() { perimeter = c.perimeter()
return items } // 18.849556
} fun printSpeed() { perimeter = c.perimeter(5F)
} // 31.415926
val numbers = }
intArrayOf(5,2,8,7,9,4,3,1)
val c = Car() Extensions
// ascending order c.accelerate() // extending the Context class with
var sortedNumbers = bubbleSort( c.decelerate() // the displayToast() function
numbers, { num1, num2 -> c.stop() fun Context.displayToast(
num1 < num2 } ) c.printSpeed() text:CharSequence,
duration:Int=Toast.LENGTH_SHORT) {
// descending order Toast.makeText(this, text,
sortedNumbers = bubbleSort( Companion Object (Static duration).show()
}
numbers, { num1, num2 ->
num1 > num2 } )
Method/Variable) // without extension
class Car { Toast.makeText(this,
companion object { "Hello, Kotlin",
// another way of passing in the
val MilesToKM = 1.60934 Toast.LENGTH_SHORT).show()
// lambda function
fun kilometersToMiles( // with extension
sortedNumbers = bubbleSort(numbers)
km:Float):Double { displayToast("Hello, Kotlin!")
{ num1, num2 -> num1 < num2 }
return km / 1.60934
}
Property Observers }
fun String.LatLng(splitter:String):
class MyPointClass { fun accelerate() {}
Pair<Float, Float> {
var x: Int by fun decelerate() {}
val latlng = this.split(splitter)
Delegates.observable(0) { fun stop() {}
return Pair(latlng[0].toFloat(),
prop, old:Int, new:Int -> fun printSpeed() {}
latlng[1].toFloat())
println(prop.name + }
}
" : from $old to $new") val v = Car.MilesToKM
var str = "1.23456,103.345678"
} val miles =
var latlng = str.LatLng(",")
} Car.kilometersToMiles(10F)
print(latlng.first)
print(latlng.second)
val pt = MyPointClass()
pt.x = 5 // x : from 0 to 5
Final Class
pt.x = 6 // x : from 5 to 6
// by default, all the classes in
// Kotlin are final (non-
Interfaces
interface CarInterface {
// inheritable)
fun accelerate() {
Vetoable Property class ClosedClass {
}
// default implementation
class MyPointClass { }
var x: Int by // error
fun decelerate()
Delegates.vetoable(0) { class Subclass0:ClosedClass() { fun accelerateBy(amount:Int)
prop, old:Int, new:Int -> } }
println(prop.name +
" : from $old to $new")
new > 0
Overriding and class MyCar:CarInterface {
override fun accelerate() {
} Overloading Methods // override implementation in
} open class Shape(length:Float, // interface
width:Float) { }
val pt = MyPointClass() var length:Float override fun decelerate() {
pt.x = 5 // x : from 0 to 5 var width:Float }
pt.x = 6 // x : from 5 to 6 init { override fun accelerateBy(amount:
pt.x = 0 // x will roll back to 6 this.length = length Int) {
this.width = width }
} }
Identity Operator open fun perimeter():Float {
class MyPointClass {
var x = 0 }
return 2 * (length + width)
Generic Class
var y = 0 open fun area(): Float { class MyStack<T> {
return length * width val elements:MutableList<T> =
constructor(x:Int, y:Int) { } mutableListOf()
this.x = x } fun push(item:T) {
this.y = y elements.add(item)
} class Circle(diameter:Float): }
} Shape(diameter / 2, diameter / 2) fun pop():T? {
var pt1 = MyPointClass(5,6) { if (elements.size>0) {
var pt2 = pt1 override fun area():Float { return elements.removeAt(
var pt3 = MyPointClass(5,6) return (Math.PI * elements.size-1)
if (pt1 === pt2) { this.length.pow(2F)).toFloat() } else {
print("Identical") } return null
} else { }
print("Not identical") override fun perimeter(): Float { }
} // Identical return (2 * Math.PI * }
if (pt1 === pt3) { this.length).toFloat() var item = myStringStack.pop()
print("Identical") } // kotlin
} else { item = myStringStack.pop()
print("Not identical") // overloading // programming
} // Not identical fun perimeter(radius:Float): Float item = myStringStack.pop() // null


Rev 1.3.1 © Wei-Meng Lee , Developer Learning Solutions, http://calendar.learn2develop.net All rights reserved.

You might also like