fun main() {
val highScores = listOf(4000, 2000, 10200, 12000, 9030)
}
.withIndex().forEachIndexed().forEach().forIndexes()abstract class Aircraft {
init { println("Aircraft = ${getName()}") }
abstract fun getName(): String
}
class Airplane(private val name: String) : Aircraft() {
override fun getName(): String = name
}
fun add(a: Int, b: Int): Int {
return a + b
}
println(add(5,10).invoke())println(::add.invoke(5, 10))println(::add.invoke{5, 10})println(add.invoke(5,10))fun static main(){}fun main(){}fun Main(){}public static void main(){}fun showHashCode(obj: Any){
println("${obj.hasCode()}")
}
fun main() {
showHashCode(1)
}
.toClass() method on the integerval task = launch {
// long running job
}
task.join()task.abort()job.stop()task.cancel()Long to an Int, not the other way aroundInt to LongLongwhen (die) {
1 -> println("die is 1")
2 -> println("die is 2")
___ -> printlin("die is between 3 and 6")
else -> printlin("die is unknown")
}
3,4,5,6in 3..63 : 6{3,4,5,6}instanceofistypeofasfirstName?.let {
println("Greeting $firstname!")
}
firstName is equal to nullfirstName is equal to an empty stringfirstName is equal to Boolean falseinline fun simple(x: Int): Int{
return x * x
}
fun main() {
for(count in 1..1000) {
simple(count)
}
}
for (_____) {
println("There are $count butterflies.")
}
count in 1..10count in 2..10 step 2count in 1..10 % 2var count=2; count <= 10; count+=2val set = setOf("apple", "pear", "orange", "apple")
println(set.count())
println(b!!.length ?: 0)println(b?.length ?: 0)println(b?.length ?? 0)println(b == null? 0: b.length)val list2 = (80..100).toList().filter(_____)
::removeBadValuesGlobalScope.removeBadValues()Mainkt.removeBadValuesremoveBadValuesfor(z in 1..7) println("$z ")for(z in 1..6) print("$z ")for(z in 1 to 6) print("$z ")for(z in 1..7) print("$z ")as???isasclass Employee
class Manager : Employee()
change()modify()set()assign()open class Employee(){
open fun display() = println("Employee display()")
}
class Supervisor : Employee() {
override fun display() {
println("Supervisor display()")
}
}
Employee.display() ::display()super.display()override.display()sealed class Status(){
object Error : Status()
class Success : Status()
}
fun main(){
var successStatus = Status.Success()
var errorStatus = Status.Error()
}
StatusError is an object, not a class and cannot be instantiatedStatus can be instantiated at a timeStatus.Error must be declared as an immutable typeStatus.Error is pribate to class and cannot be declared externallyval seq = sequence { yieldAll(1..20) }
.filter { it < 11 }
println(seq)
.toList().filter{ it < 11 } should be .filter{ it > 11 }yieldAll(1..20) should be yieldAll(1..10)class Person
equals(), hashCode(), and toString()equals(), toHash(), and super()print(), println(), and toString()clone(), equals(), and super()object DatabaseManager {}singleton DatabaseManager {}static class DatabaseManager {}data class DatabaseManager {}abstract class Person(val name: String) {
abstract fun displayJob(description: String)
}
displayJob() methodimport com.tekadept.app.model.User
import com.tekadept.app.database.User
class UserService{
fun translateUser(user: com.tekadept.app.database.User): User =
com.tekadept.app.model.User("${user.first} ${user.last}")
}
obj.classInfo()obj.typeInfo()obj::class.simpleNameobj::classval arrs[5]: Intval arrs = IntArray(5)val arrs: Int[5]val arrs = Array<Int>(5)internalprivatepublicprotected== determines if two primitive types are identical. === determines if two objects are identical== determines if two references point to the same object. === determines if two objects have the same value== determines if two objects have the same value. === determines if two strings have the same value== determines if two objects have the same value. === determines if two references point to the same objectval max3 = a.max(b) (Extension Function is One of the idiomatic Solutions in Kotlin)val max = a > b ? a : bval max = if (a > b) a else bif (a > b) max = a else max = benum class Signal { OPEN, CLOSED, SENDING }
println(Signal.SENDING.position())println(Signal.SENDING.hashCode())println(Signal.SENDING)println(Signal.SENDING.ordinal)class Detail {
companion object {
const val COLOR = "Blue"
@JvmField val SIZE = "Really Big"
}
}
const is compatible with Java, but @JvmField is not@JvmFieldopen class Attribute
class Href: Attribute()
class Src: Attribute()
class Alt: Attribute()
fun getAttribute(attribute: Attribute) : String {
return when (attribute) {
is Href -> "href"
is Alt -> "alt"
is Src -> "src"
else -> "unknown"
}
}
open with closedopen with sealedopen with privateopen with publicDelegates.watcher()Delegates.observable()Delegates.rx()Delegates.observer()val addend = 1
infix fun Int.add(added: Int=1) = this + addend
fun main(){
val msg = "Hello"
println( msg shouldMatch "Hello")
println( 10 multiply 5 + 2)
println( 10 add 5)
}
it, not this, as the default parameter nameval name = nullvar name: Stringval name: Stringval name: String? = nullval len: Int = if (x != null) x.length else -1
val len = x?.let{x.len} else {-1}val len = x!!.length ?: -1val len:Int = (x != null)? x.length : -1val len = x?.length ?: -1fun String.shouldEqual(value: String) = this == value
fun main(){
val msg = "test message"
println(msg shouldEqual "test message")
}
publicoperator to the shouldMatch extension functionprintln(msg.shouldEqual("test message")))infix to the shouldMatch extension functionclass Record{
companion object {
const val COLOR = "Red"
val SIZE = "Large"
}
}
COLOR and SIZE are both immutable, they are identical internallyCOLOR slower and less space efficient than SIZECOLOR faster, but not compatible with Java. Without const, SIZE is still compatible with JavaCOLOR faster and more space efficient than SIZEclass Cat (name: String) {
fun greet() { println("Hello ${this.name}") }
}
fun main() {
val thunderCat = Cat("ThunderCat")
thunderCat.greet()
}
main().newthis.namevar to valNote: By default, constructor parameters can only be used in the initializer blocks or property initializers declared in the class body. Therefore, to let the greet function have access to the name parameter, it should be declared as a property: class Cat (val name: String) { ... }
var ndx = 0;
for (value in 1..5){
println("$ndx - $value")
ndx++
}
for( (ndx, value) in (1..20).withIndex() ){for( (ndx, value) in (1..20).pair() ){for( Pair(ndx, value) in 1..20 ){for( (ndx, value) in *(1..20) ){a.from(b)a.range(b)a.rangeTo(b)a.to(b)data class Project(var codeName: String, var version: String)
fun main(){
val proj = Project("Chilli Pepper", "2.1.0")
}
proj.0proj[0]proj[1]proj.component1()fun fibonacci() = sequence {
var params = Pair(0, 1)
while (true) {
___(params.first)
params = Pair(params.second, params.first + params.second)
}
}
with()yield()skip()return()for(y in 1..100) y+=2
y must be declared with var to be mutabley is an implicitly immutable valuey can change only in a while loopy, it must be declared outside of the loopdata class Point(val x: Int, val y: Int)
operator fun Point.plus(other: Point) = Point(x + other.x, y + other.y)
operator fun Point.hash(other: Point) = Point(x - other.x, y - other.y)
fun main() {
val point1 = Point(10, 20)
val point2 = Point(20, 30)
println(point1 + point2)
println(point1 # point2)
}
minus instead of hash, then type alias the minus symbol.infix.val result = generateSequence(1) { it + 1 }.toList()
println(result)
it finite.generateSequence(0).it parameter should be replaced with this.fun main() {
val students = arrayOf("Abel", "Bill", "Cindy", "Darla")
printStudents(students)
}
fun printStudents(vararg students: String) {
for(student in students) println(student)
}
printStudents(students.toList())printStudents(students!!)printStudents(*students)printStudents(students[])val y = arrayOf(10, 20, 30, 40)
val z = listOf(10, 20, 30, 40)
y but not z.y and z are a type alias of the same type.z since it is a list.z but not y.fun main() = runBlocking {
val task = GlobalScope.launch {
delay(1000L)
println("there")
}
println("Hello,")
}
task.complete()task.wait()task.join()task.cancel()data class Student(val firstName: String, val lastName: String)
println(students.groupBy{ it.lastName }.count())println(students.groupBy{ it.lastName.first() }.fold().count())println(students.groupingBy{ it.lastName.first() }.count())println(students.groupingBy{ it.lastName.first() }.size())open class AA() {
var price: Int = 0
get() = field + 10
}
class BB() : AA() {
var price: Int = 0
get() = field + 20
}
lateinit modifier to AA.price.override modifier to BB.price.open modifier to AA.price and an override modifier to BB.price.public modifier to AA.price and a protected modifier to BB.price.val quote = "The eagle has landed."
println("The length of the quote is $quote.length")
21The eagle has landed..lengthfun main() {
val highScores = listOf(4000, 2000, 10200, 12000, 9030)
.sortedByDescending().descending().sortedDescending().sort("DESC")lateinit var name: String // lateinit is modifier not delegatevar name: String by lazyvar name: String by Delegates.notNull()var name: String? = nullDelegates.vetoable()Delegates.cancellable()Delegates.observer()Delegates.watcher()val sorted = fibonacci().skip(3).take(6).sortedDescending().toList()val sorted = fibonacci().skip(3).take(6).sortedByDescending().toList()val sorted = fibonacci().skip(3).limit(6).sortedByDescending().toList()val sorted = fibonacci().drop(3).take(6).sortedDescending().toList()val a = arrayOf(1, 2, 3)
val b = arrayOf(100, 200, 3000)
val c = list of (a, b)val c = a + bval c = listOf(a+b)val c = listOf(*a, *b)println("length of First Name = ${firstName!!.length}")
!!. with ?.!!. with ?:.!!. with ?.let.class Styles {
companion object {
const val COLOR = "Blue"
@JvmField val SIZE = "Really big"
}
}
const works only with strings and primitives. @JvmField does not have that restriction.@JvmField works as a top-level variable, but const works only in a class.@JvmField is compatible with Java, but const is not.@JvmField is always inlined for faster code.yield() function or check the isActive property.cancelled() function or check the isActive property.stillActive() function or check the isCancelled property.checkCancelled() function or check the isCancelled property.data class Student (val name: String, var location: String) {
fun moveTo (newLoc: String) { location = newLoc }
}
fun main() {
Student ("Snow", "Cologne").run {
this.moveTo ("LA")
}
moveTo("LA")::moveTo("LA")_.moveTo("LA")it.moveTo("LA")var price: Int = 0
public get()
private set
var price: Int = 0
private set
var price: Int = 0
val set
val price: Int=0
class SpecialFunction : () -> Unit {
override fun invoke() {
println("Invoked from an instance.")
}
}
fun main() {
try { SpecialFunction()() }
catch (ex: Exception) { println("An error occurred") }
}
SpecialFunction()().invoke() method.val mileage:Int = 566var mileage:Int = 566val mileage = 566 (Note: inferred)const int mileage = 566var longInt = 10Lconst long longInt = 10val longInt = 10Lval longInt:Long = 10val binaryStr = "00001111"
val myInt = toInt(binaryStr)val myInt = binaryStr.toInt("0b")val myInt = binaryStr.toInt()val myInt = binaryStr.toInt(2)Any program line can be marked with a labelAny statement can be marked with a labelAny expression can be marked with a labelOnly the beginning of loops can be marked with a labelDefaultSuperAnyObjectComparable interface. How can you restrict the function?fun sort(list: List<T>): List <T> {
return list.sorted()
}
<T -> Comparable<T>> between the fun keyword and the function nameComparable<T> between the fun keyword and the function name<T : Comparable<T>> between the fun keyword and the function name<T where Comparable<T>> between the fun keyword and the function nameval names = arrayOf<String>(3)
names[3]= "Delta"
printlln()?fun main() {
val name: String = "Amos"
val grade: Float = 95.5f
println("My name is " + name + ". I score " + grade + " points on the last coding quiz.")
}
new printf().string.format instead.string append instead.```class Empty
```