A selection of some of the most frequent questions about Kotlin on Stack Overflow, asked, answered and explained. Something in there for everyone, from beginners to experts.
to initialize • Array<Int> Might be required by an API Can store nullable values val intArray = IntArray(10) val arrayOfInts = Array<Int>(5) { i -> i * 2 } val notPeople: Array<Person?> = arrayOfNulls<Person>(13)
Usually the best choice • Sequence To handle an infinite number of elements For huge collections, judiciously • Stream When interoperating with Java
for (i in 0..args.lastIndex) { println(args[i]) } for (i in 0 until args.size) { println(args[i]) } for (i in args.indices) { println(args[i]) } for (arg in args) { println(arg) }
for (i in 0..args.lastIndex) { println(args[i]) } for (i in 0 until args.size) { println(args[i]) } for (i in args.indices) { println(args[i]) } for (arg in args) { println(arg) } args.forEach { arg -> println(arg) }
for (i in 0..args.lastIndex) { println(args[i]) } for (i in 0 until args.size) { println(args[i]) } for (i in args.indices) { println(args[i]) } for (arg in args) { println(arg) } args.forEach { arg -> println(arg) }
for (i in 0..args.lastIndex) { println(args[i]) } for (i in 0 until args.size) { println(args[i]) } for (i in args.indices) { println(args[i]) } for (arg in args) { println(arg) } args.forEach { arg -> println(arg) }
Foo.f() Foo.Companion.f(); Companion object with @JvmStatic Foo.f() Foo.f(); Object Foo.f() Foo.INSTANCE.f(); Object with @JvmStatic Foo.f() Foo.f(); Top level function f() UtilKt.f(); Top level function with @JvmName* f() Util.f(); * With the @JvmName annotation on the file use-site target
X.x X.Companion.getX(); Companion object with @JvmStatic X.x X.getX(); Companion object with @JvmField X.x X.x; Companion object with const X.x X.x; Object X.x X.INSTANCE.getX(); Object with @JvmStatic X.x X.getX(); Object with @JvmField X.x X.x; Object with const X.x X.x; Top level variable x ConstKt.getX(); Top level variable with @JvmField x ConstKt.x; Top level variable with const x ConstKt.x; Top level variable with @JvmName* x Const.getX(); Top level variable with @JvmName* and @JvmField x Const.x; Top level variable with @JvmName* and const x Const.x; * With the @JvmName annotation on the file use-site target
null) { fun play() { if (toy != null) { toy.chew() } } } Kotlin: Smart cast to 'Toy' is impossible, because 'toy' is a mutable property that could have been changed by this time
button); } class KtListener : OnClickListener { override fun onClick(button: Button?): Unit { val name = button?.name ?: "Unknown button" println("Clicked ${name}") } }
button); } class KtListener : OnClickListener { override fun onClick(button: Button?): Unit { val name = button?.name ?: "Unknown button" println("Clicked ${name}") } }
button); } class KtListener : OnClickListener { override fun onClick(button: Button?): Unit { val name = button?.name ?: "Unknown button" println("Clicked ${name}") } }