Skip to content

Instantly share code, notes, and snippets.

View MostafaNasiri's full-sized avatar
🍂

MostafaNasiri

🍂
View GitHub Profile
fun main() {
// Example 1 (Array)
val nums = arrayOf(1, 2, 3, 4, 5)
for (n in nums) {
println(n)
}
// Example 2 (Collection)
val names = listOf("Arthur", "John", "Dutch")
fun main() {
val nums = intArrayOf(1, 3, 5, 7, 9)
println(nums.size)
println(nums[1])
// You can have an array of values with different types
val items = arrayOf(1, "Tom", 3.14)
}
fun main() {
val name: String? = "Jack"
name?.let {
println("Your name is: " + it)
println("Your name has " + it.length + " characters")
}
}
fun main() {
var x = 1
while (x <= 5) {
println(x)
x++
}
val y = false
do {
println("do while loops execute at least once")
fun main() {
// Example 1
val firstNum = 1
val message = when (firstNum) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Unknown Number" // "else" is mandatory here
}
fun main() {
// Example 1
val x = 2
// Just a simple if expression
if (x % 2 == 0) {
println("Even")
}
// Example 2
fun main() {
var name: String? = "Arthur"
var nameLength = name!!.length // nameLength = 6
name = null
nameLength = name!!.length // KotlinNullPointerException
}
fun main() {
var name: String? = null
// name?.length evaluates to null so the elvis operator
// chooses the second value:
val nameLength = name?.length ?: 0 // nameLength = 0
}
fun main() {
var name: String? = "joey"
if (name != null) {
val nameLength = name.length
}
// The same thing can be done in a much shorter way:
var nameLength = name?.length // nameLength = 4
fun main() {
var firstName: String = null // Error: You can't assign null to a non-null type
// The question mark tells the compiler that this variable can hold null:
val lastName: String? = null
// You can't assign a nullable variable to a non-null type
// even though they're both Strings: