Skip to content

Instantly share code, notes, and snippets.

View MostafaNasiri's full-sized avatar
🍂

MostafaNasiri

🍂
  • 05:56 (UTC +03:30)
View GitHub Profile
fun main() {
var city: String = "New York"
// You can omit the type if you declare and initialize a variable at the same time
var city = "New York"
// But you can't do something like this:
var city // Error: Either specify the variable type or initialize it
city = "New York"
fun main() {
val anInt = 2
val aLong: Long = anInt // Error: Type mismatch
aLong = anInt.toLong() // This is correct
val stringNum = "123"
val num = stringNum.toInt()
}
interface Processor<T> {
fun process(): T
}
class ExampleProcessor : Processor<Unit> {
override fun process() {
// Do something
}
}
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:
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 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? = "Arthur"
var nameLength = name!!.length // nameLength = 6
name = null
nameLength = name!!.length // KotlinNullPointerException
}
fun main() {
// Example 1
val x = 2
// Just a simple if expression
if (x % 2 == 0) {
println("Even")
}
// Example 2
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() {
var x = 1
while (x <= 5) {
println(x)
x++
}
val y = false
do {
println("do while loops execute at least once")