Learning the Kotlin language is easy.
Here is the cheatsheet for your reference!
Print Hello World
fun main() { println("Hello World") }
Variable Mutable and Immutable
var mutableVar = "Hello" mutableVar = "World" val immutableVar = "Hello World"
Challenge
What happens when you set another value to
immutableVar
?Strong Typing and Inference
val stringVariable = "Type is inferred as String" val doubleVariable = 120.3 val explicitTyping: Int explicitTyping = 202
Challenge
What happens when you set the value of another type to the above variable?
Type Conversion
val one = 1 val oneHundred = "100" val sum = oneHundred.toInt() + one
String Interpolation
val integerInsideString = "I am Mozzlog. I was born at 2023"
Basic Data Type
val integerValue = 1 val doubleValue = 1.2 val floatValue: Float = 1.23f val stringValue = "this is string" val tupleValue = Pair(integerValue, doubleValue)
Collection Basic: Array
val arrayOfString = arrayOf("Hello", "World") val arrayOfInteger = arrayOf(1, 2) val arrayOfDouble = arrayOf(10.0, 21.2) val mixedArray = arrayOf("String", 1, 10.2)
Challenge
What is the type of
mixedArray
?Collection Key Value: Dictionary (Map)
val dictWithKeyStringAndValueString = mapOf( "Hello" to "World", "Good" to "Morning" ) val dictWithKeyStringAndValueAny = mapOf( "Hello" to 1, "Good" to "Morning" ) val dictWithKeyAnyAndValueString = mapOf( "Hello" to "World", 1 to "Morning" )
Collection Without Duplication: Set
val setOfNames = setOf("Kotlin", "Swift")
Function
fun sayHelloWorld() { println("Hello World") }
Function With Parameter
fun sayMyName(name: String) { println("Your name is $name") } sayMyName("Heisenberg")
Function With Return Value
fun getReturnValue(value: Int): Int { return value } val value = getReturnValue(1002)
Function With Return Type Tuple (Pair)
fun createTuple(value: Int): Pair<Int, Int> { return Pair(value, value) } val (value1, value2) = createTuple(231)
Class
class StandardClass
Class With Member
class StandardClass { val member = "default" fun printMember() { println(member) } } val obj = StandardClass() obj.printMember()
Class With Initializer
class StandardClass(val memberInt: Int, var memberDefault: String = "") { init { memberDefault = "changed" } } val obj = StandardClass(20) val obj2 = StandardClass(20, "changed")
Data Class
data class StandardStruct(val memberInt: Int, var memberDefault: String = "")
Challenge
Can you change the value of
memberDefault
after StandardStruct
instantiation?Hint
Use
var
instead of val
.