🍵 kotlin kotlin cheat sheet

kotlin

fukurou

the supreme coder
ADMIN
Kotlin:
*variables*

var age = 0 // implicit var declaration
var isCompleted = false // explicit var declaration
val test = 3; // constant

*strings*
var s1:String = "hello"
val result:String = "hello $name"

*classes*
class MyClass: Any() {
    var myProperty = 12
    // methodes
}
val mClass = MyClass() // object instance

*methods*
fun myMethod(): Boolean? {
    return true
}

fun methodWithParams(a: Int, b: Int): Int {
    return a + b
}

*varargs*
    fun sum1(vararg values: Int): Int {
        var total = 0
        for (i in values.indices) {
            total += values[i]
        }
        return total
    }
println(mClass.sum1(1,2,4))

*arraylist*
val cars = ArrayList<String>() // Create an ArrayList object

*array*
val num = Array(3, {i-> i*1})
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")

// access element at index 0
cars[0] = "jag";

*dictionary*
import java.util.*

    val dic1: Hashtable<String, Int> = Hashtable()
    dic1["one"] = 1
    dic1["two"] = 2
    val e = dic1.keys()
    while (e.hasMoreElements()) {
        // Getting the key of a particular entry
        val key = e.nextElement()
        // Print and display the Rank and Name
        println("key : " + key + " value " + dic1[key])
    }

*if*
val time = 20
if (time < 18) {
    println("Good day.")
} else {
    println("Good evening.")
}
val s1:String = if (bool1) "true" else "false"
*** you are here
*loops*
for (i in 1..10) {}
for (i in arr) {} // for each item loop
while (bool) {}

do{}
while (bool)

*switch*

when (expression) {
    "x" -> {}
    "y" -> {}
    else -> {}
}

*randomizer*
import java.util.*

val rand = Random() // instance of random class
val int_random: Int = rand.nextInt(upperbound) // 0->upperbound -1
val double_random: Double = rand.nextDouble() // 0->1
val float_random: Float = rand.nextFloat() //0->1

*N-dimensional arrays*
val arr = Array(10) { IntArray(20) }
arr[0][0] = 1
 
Top