Declare var for a mutable variable:
var name = "Mommy"
name = "Uma"
Declare val for a read-only constant:
val pi = 3.14
Increment and decrement operators:
var toyCount = 4
toyCount++
toyCount--
Double for decimal values:
var starValue: Double = 0.1
Boolean for true/false values:
var isPlaying = true
fun greeting(): String {
return "Hello!"
}
println(greeting())
class Person(var name: String)
val person = Person("John")
person.name = "Jane"
val numbers = mutableListOf(1,2,3)
numbers.add(4)
val numsSet = setOf(1,2,3)
println(numsSet.contains(2))
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}
val result = max(1, 2)
var name: String? = null
name = "John"
fun String.initials(): String {
return this.split(" ").map { it.first() }.joinToString("")
}
val name = "John Doe"
println(name.initials())
val numbers = listOf(1,2,3)
numbers.forEach { println(it) }
fun sum(a: Int, b: Int): Int {
return a + b
}
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
val result = calculate(1, 2, ::sum)
class Box<T>(t: T) {
var value = t
}
val box = Box(1)
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}