随笔分类 - Kotlin
摘要:import java.util.* class Animal { var age = 0 get() = field set(value) { if(value >= 0) { field = value } else { throw Error("bad number") } } } fun m
阅读全文
摘要:enum class Color { RED, GREEN, BLUE } fun main() { println(Color.GREEN) // GREEN } Or give enum a value: enum class Color { RED(0xFF0000), GREEN(0x00F
阅读全文
摘要:Singleton Object need to be defined as global variable: object Cache { val name= "Cache" fun retrieveDate(): Int { return 0 } } fun main() { println(C
阅读全文
摘要:If we want to use Class to represent a piece of data such as Object, we can use Data class instead of normal class. Difference: Data class has better
阅读全文
摘要:interface Lendable { fun borrow() } // The properties title, genre, and publicationYear can be included in the parent class because both books and DVD
阅读全文
摘要:import java.util.* /** * You can edit, run, and share this code. * play.kotlinlang.org */ abstract class Course(val topic: String, val price: Double)
阅读全文
摘要:import java.util.* /** * You can edit, run, and share this code. * play.kotlinlang.org */ interface Driveable { fun drive() } interface Buildable { va
阅读全文
摘要:open class Person (open val name: String = "", open var age: Int) { init {} open fun greeting(pn: String) { println("$name says hello to $pn") } } cla
阅读全文
摘要:class Person (val name: String, var age: Int) { init {} fun greeting(pn: String) { println("$name says hello to $pn") } } fun main() { val p = Person(
阅读全文
摘要:fun reverse(numbers: List<Int>): List<Int> { var res = arrayListOf<Int>() for (i in 0..numbers.size-1) { res.add(numbers.get(numbers.size - 1 - i)) }
阅读全文
摘要:It is possible to give loop a name, it is useful when dealing with nested loop: fun main() { outer@ for (i in 1..10) { for (j in 1..10) { if (i - j ==
阅读全文
摘要:fun main() { val list = listOf("Java", "Kotlin", "Python") for (element in list) { println(element) } for ((index, value) in list.withIndex()) { print
阅读全文
摘要:Array is mutable, but fixed length. Which means you can modify items in the Array, but you cannot add / remove item; // Array is fixed length, you can
阅读全文
摘要:Difference between "when" and Javascript "switch". In Switch, you have to call "break"; but "when", you don't need to. In Switch, the case expression
阅读全文
摘要:fun main() { val mode = 2 val result = when (mode) { 1 -> "1 is ok" 2 -> { println("2 is fine") val i: Int = 3 "return string 2 is fine" } else -> "la
阅读全文
摘要:fun main() { val mode = 3 when (mode) { 1 -> print("1 is ok") 2 -> { print("2 is fine") print("2 is fine") } else -> { print("large than 2 is not ok")
阅读全文
摘要:In Kotlin, it helps to avoid null reference, which means by default you cannot assign null value to any variable; But if you do want to assign null to
阅读全文
摘要:fun main() { val a = 4 val b: Byte = 127 val c: Short = 123 val d: Int = 7 val e: Long = 123456789 val f: Float = 3.73f val g: Double = 3.73 val h: Ch
阅读全文
摘要:using 'var', variable can be reassigned. using 'val', variable cannot be ressiagned. the same as Javascript 'const'.
阅读全文