Kotlin Cheat Sheet
Hi Everyone, this time I come up with something new rather than Understanding concept. I prepared Cheat Sheet for Kotlin Programming Language for quick reference.
Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is a new programming language for the JVM. It produces Java bytecode, supports Android and generates JavaScript.
Basics
- You do not need
;
to break statements. - There are two keywords for variable declaration, var and val.
- var : var is like a general variable and can be assigned multiple times and is known as the mutable variable in Kotlin
- val : val is a constant variable and can not be assigned multiple times and can be Initialized only single time and is known as the immutable variable in Kotlin.
- The keyword
void
common in Java or C# is calledUnit
in Kotlin. - Unlike Java or C#, you declare the type of a variable after the name, e.g.
var firstName : String
- Strings :
val name = "Peter"
val newVar = "Hello, " + name
val helloName = "Hello, $name"
val upercaseName = "Hello, ${name.toUpperCase()
2. Booleans :
val trueBoolean = true
val falseBoolean = false
val andCondition = trueBoolean && falseBoolean
val orCondition = trueBoolean || falseBoolean
3. Floats :
val intNumber = 10
val doubleNumber = 10.0
val longNumbe = 10L
val floatNum = 10.0F
4. Mutability :
var mutableString: String = "Hello"
val immutableString: String = Hello"
5. Companion objects Syntax :
class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
}
6. Null Safety :
Nullable properties
val cannotBeNull: String = null // Invalid
val canBeNull: String? = null // Validval cannotBeNull: Int = null // Invalid
val canBeNull: Int? = null // Valid
Null Checking
val name: String? = "Hello"if (name != null && name.length > 0) {
print("String length is ${name.length}")
} else {
print("String is empty.")
}
!! operator
val opt = name!!.length
the not-null assertion operator (!!
) converts any value to a non-null type and throws an exception if the value is null
. You can write name!!
, and this will return a non-null value of name (for example, a String
in our example) or throw an NPE if name is null
Safe Casts
val opt: Int? = a as? Int
Regular casts may result in a ClassCastException
if the object is not of the target type. Another option is to use safe casts that return null
if the attempt was not successful.
7. Classes :
Classes in Kotlin are declared using the keyword class
class Student{ /*...*/ }
Primary Constructor
class Student(val name: String, val age: Int)
val student1 = Student("Peter", 11)
Secondary Constructor
class Student(val name: String) {
private var age: Int? = null constructor(name: String, age: Int) : this(name) {
this.age = age
}
}// Above can be replaced with default params
class Student(val name: String, val age: Int? = null)
Enum Class
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}
Data Class
data class Student(val name: String, val age: Int)
8. Functions :
Kotlin functions are declared using the fun
keyword:
fun printStudentName() {
print("Richa")
}
Parameters & Return Types
fun printStudentName(student: Student) {
print(student.name)
}
Default Parameters
fun getStudentName(student: Student, intro: String = "Hello,") {
return "$intro ${student.name}"
}
9. Collections
List
val numbers = listOf("one", "two", "three", "four")
Set
val numbers = setOf(1, 2, 3, 4)
Map
A Map
stores key-value pairs (or entries); keys are unique, but different keys can be paired with equal values.
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
10. Control Flows
Conditions and loops
“if” Statement
if
is an expression: it returns a value
var max = a
if (a < b) max = b
// With else
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// As expression
val max = if (a > b) a else b
when
when
defines a conditional expression with multiple branches.
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
for
for (item in collection) print(item)
If you want to know more about null concept please go through my blog Kotlin: Null Safety Concept for basic understanding.
Happy Reading :)