Learn Kotlin in 30 Min

1. Function

fun function() {
print("")
}

fun functionWithParam(param: Int) {
print(param)
}

fun functionWithReturn(): Int {
return 100
}

fun functionWithParamReturn(param: Int): Int {
return param + 100
}

fun shortFunction(param: Int): Int = param

2. var vs. val

fun varExample() {
var variable = 1
variable += 1
variable = 10

var variable2: Int
variable2 = 10
variable2 = 20
}

fun valExample() {
val value = 1
// value += 1 Error occur
// value = 10 Error occur

val value2: Int
value2 = 10
// value2 = 20 Error occur
}

3. String template

fun stringTemplate() {
val name = "name"
print("My name is " + name)
print("My name is $name.")
print("My name is ${name}.")
}

4. If statement

fun ifStatement() {
val age = 19
if (age < 19) {
print("kids")
} else {
print("adult")
}
}
fun inlineIfStatement(age: Int) = if (age < 19) "kids" else "adult"

fun whenStatement() {
var age = 19
when (age) {
in 0..18 -> "kids"
in 19..120 -> "adult"
else -> "hero"
}
}

5. Array, List, ArrayList

// Array
fun array() {
var array = arrayOf(1, 2, 3, 4)

print(array[0])
print(array.get(0))

array[0] = 1

// array.add(5) Error occur
}

// Immutable List
fun list() {
var list = listOf(1, 2, 3, 4)

print(list[0])
print(list.get(0))
}

// Mutable list
fun mutableList() {
var mutableList = mutableListOf(1, 2, 3, 4)
mutableList[0]
mutableList.get(0)
mutableList.add(5)
mutableList.removeAt(0)
mutableList.remove(5) // returns true
mutableList.remove(6) // returns false

var arrayList = arrayListOf(1, 2, 3, 4)
arrayList[0]
arrayList.get(0)
arrayList.add(5)
arrayList.removeAt(0)
arrayList.remove(5) // returns true
arrayList.remove(6) // returns false
}

6. Loop

fun loop() {
var alphabets = listOf("A", "B", "C", "D")
for (alphabet in alphabets) {
print(alphabet)
}

for ((index, alphabets) in alphabets.withIndex()) {
print("${index}, ${alphabets}")
}

for (i in 1..10) {
print(i)
}

var i = 0
while (i < 10) {
print(i)
i++
}
}

7. Non-nullable vs. Nullable

fun nullable() {
var nonNullableString: String = "string"
nonNullableString.uppercase()
nonNullableString[0]

// var nullableString: String = null Error Occur
var nullableString: String? = null
// nullableString.uppercase() Error
// nullableString[0] Error

// ?. operator
nonNullableString?.uppercase() // returns "STRING"
nonNullableString?.get(0) // returns "s"
nullableString?.uppercase() // returns null
nullableString?.get(0) // returns null

// ?: operator (aka. Elvis operator)
nonNullableString ?: "default" // returns "string"
nonNullableString?.uppercase() ?: "default" // returns "STRING"
nullableString ?: "default" // returns "default"
nullableString?.uppercase() ?: "default" // returns default

// Throws Index out of bound Error
// nullableString?.get(0) ?: throw IndexOutOfBoundsException()

// prints "The value is string"
nonNullableString?.let { value ->
print("The value is ${value}")
}
// does not print
nullableString?.let { value ->
print("The value is ${value}")
}

// value-parameter can be omitted
nullableString?.let {
print("The value is ${it}")
}
}

8. Class

class Person(var name: String, var age: Int) {
lateinit var hobby: String // recommended to use private

init {
print("Printed this when a class is instantiated")
}

constructor(
name: String,
age: Int,
hobby: String
) : this(name, age) {
this.hobby = hobby
}

fun nextYear() {
age++
}
}

fun createPerson() {
var person = Person("chris", 20)
print(person.age)
// print(person.hobby) // Not Initialized error occur

var person2 = Person("chris", 20, "debugging")
print(person2.age)
print(person2.hobby)
person2.nextYear()

9. Lambda

fun lambdaExample() {
var result: (name: String, age: Int) -> (String) =
{ name, age ->
"My name is ${name}, and I'm ${age} years old"
}

// Inference type
var result2 = { name: String, age: Int ->
"My name is ${name}, and I'm ${age} years old"
}

var printPretty: String.() -> String = {
"My name is ${this}"
}
"chris".printPretty() // returns "My name is chris"

var printPretty2: String.(age: Int) -> String = {
"My name is ${this}, and I'm ${it} years old"
}
"chris".printPretty2(20) // returns "My name is chris, and I'm 20 years old"

var printPretty3: String.(age: Int, hobby: String) -> String =
{ age, hobby ->
"My name is ${this}, and I'm ${age} years old, and hobby is ${hobby}"
}
"chris".printPretty3(20, "debugging")
// returns "My name is chris, and I'm 20 years old, and hobby is debugging"

fun invokeLambda(lambda: (Int) -> Boolean): Boolean {
return lambda(1)
}

var result3 = invokeLambda {
it
> 10
}

fun invokeLambda2(
score: Int,
lambda: (Int) -> Boolean
): Boolean {
return lambda(score)
}

var result4 = invokeLambda2(1) {
it
> 10
}
}

10. Data class

fun dataClassExample() {
data class PersonData(
var name: String,
var age: Int
)

var person = PersonData("chris", 20)
person.toString() // returns "PersonData(name=chris, age=20)"
person.age++
person.name = "Anonymous"
}

11. Companion object

class PersonCompanion(var name: String, var age: Int) {
companion object {
private const val MAX_AGE = 120
fun create(
name: String,
age: Int = MAX_AGE
): Person {
return Person(name, age)
}
}
}

fun companionExample() {
var person =
PersonCompanion.Companion.create("chris", 20)
var person2 = PersonCompanion.create("chris", 20)
var person3 = PersonCompanion.create("chris")
person3.age // returns 120
}

12. Object

data class Ticket(val price: Int)

object TicketFactory {
val tickets = arrayListOf<Ticket>()
fun addTicket(price: Int) {
tickets.add(Ticket(price))
}
}

fun objectExample() {
TicketFactory.addTicket(1)
TicketFactory.addTicket(1)
TicketFactory.addTicket(1)
TicketFactory.tickets.size // returns 3
}

All together

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store