1. Variable:
var a = 10
val b = 10
var c: Int = 10
2. Format String:
val name = "cat"
println("Hello ${name}")
3. Function:
fun greet(name: String=""): Unit {
println("Hello ${name}")
}
fun greet(name: String=""): Unit =
println("Hello ${name}")
4. For loop/ For in:
for(i in [..|until|] [step]) {}
val lst = listOf(1, 2, 3)
for(it in lst) println("item: ${it}")
val m = mapOf(
"Hello" to "world", "apple" to "banana")
for((k, v) in m) println("key: ${k}, val: ${v}")
5. Lambda:
val greet = { name:String -> println("Hello ${name}") }
greet("Carto")
6. Funtional style:
val lst = listOf(10, 20, 11, 30)
lst.forEach { it -> println(it) }
val odd = lst.filter { it %2 != 0 }
val double = lst.map { it -> it*2 }
7. DTOs, class, object and abstract:
data class Dog(val name:String, val age:Int) {}
fun main(args: Array<String>) {
val d1 = Dog("Doggy", 10)
val d2 = Dog("Doggy", 10)
val d3 = Dog("White", 10)
println(d1 == d2)
println(d2 == d3)
}
8. Instantiate an abstract class:
abstract class Dog {
abstract fun bark()
}
val d = object: Dog() {
override fun bark() {
println("Bark bark")
}
}
d.bark()
9. try-catch/if expression:
val y = if (x == 1) {
"one"
} else if (x == 2) {
"two"
} else {
"other"
}
留言
張貼留言