Skip to content

Instantly share code, notes, and snippets.

Mostafa MostafaNasiri

Block or report user

Report or block MostafaNasiri

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
View for_loop.kt
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")
View arrays.kt
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)
}
View let.kt
fun main() {
val name: String? = "Jack"
name?.let {
println("Your name is: " + it)
println("Your name has " + it.length + " characters")
}
}
View while_loops.kt
fun main() {
var x = 1
while (x <= 5) {
println(x)
x++
}
val y = false
do {
println("do while loops execute at least once")
View when.kt
fun main() {
// Example 1
val firstNum = 1
val message = when (firstNum) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Unknown Number" // "else" is mandatory here
}
View if.kt
fun main() {
// Example 1
val x = 2
// Just a simple if expression
if (x % 2 == 0) {
println("Even")
}
// Example 2
View notnull_assertion.kt
fun main() {
var name: String? = "Arthur"
var nameLength = name!!.length // nameLength = 6
name = null
nameLength = name!!.length // KotlinNullPointerException
}
View elvis.kt
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
}
View safe_call.kt
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
View nullability_1.kt
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:
You can’t perform that action at this time.