You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
var batteryPercentage =80// long syntax
batteryPercentage = batteryPercentage +10// short syntax with augmented assignment operator
batteryPercentage +=10
var morning =trueif (morning) {
println("Rise and shine!")
}
// Print: Rise and shine!
Else-expression
var rained =falseif (rained) {
println("No need to water the plants today.")
} else {
println("The plant needs to be watered!")
}
// print: The plant needs watering!
Else-If expressions
var age =65if (age <18 ) {
println("You are considered a minor")
} elseif (age <60) {
println("You are considered an adult")
} else {
println("You are considered senior")
}
// print: you are considered senior
var humid =truevar raining =truevar shorts =falsevar sunny =false// true AND trueprintln(humid && raining) // true// true AND falseprintln(humid && shorts) // false// false AND trueprintln(sunny && raining) // false// false AND falseprintln(shorts && sunny) // false
Or operator:||
var late =truevar skipBreakfast =truevar underslept =falsevar checkEmails =false// true OR trueprintln(skipBreakfast || late) // true// true OR falseprintln(late || checkEmails) // true// false OR trueprintln(underslept || late) // true// false OR falseprintln(checkEmails || underslept) // false
NOT operator
var hungry =truevar full =falseprintln(!hungry) // falseprintln(!full) // true
Evaluation order
!true&& (false||true) // false/*(false || true) is evaluated first to return true.Then, evaluate !true && true and return the final result false*/!false&&true||false// true/*!false is evaluated first to return true.Then true && true is evaluated, returning true.then, true || evaluates to false and eventually returns true*/
Nested conditions
var studied =truevar wellRested =trueif (wellRested) {
println("Good luck today!")
if (studied) {
println("You should prepare for the exam!")
} else {
println("Spend a few hours studying before the exam!")
}
}
// Print: Good luck today!// print: You should be ready for the exam!
When expression
var grade ="A"when (grade) {
"A"->println("Great job!")
"B"->println("Great job!")
"C"->println("You passed!")
else->println("Close! Be sure to prepare more next time!")
}
// print: Great job!
Range operator
var height =46// inchesif (height in1..53) {
println("Sorry, you must be at least 54 inches to ride the coaster")
}
// Prints: Sorry, you must be at least 54 inches to ride the roller coaster
var a:String="Kotlin"// a can never be null
a =null// compilation errorvar b:String?="Kotlin"// b can be null
b =null// ok
Safe-Calls
val a ="Kotlin"val b:String?=nullprintln(a.length) // can be called safely, because a is never nullprintln(b?.length) // b?.length returns the length of b, or null if b is nullprintln(a?.length) // Unnecessary safe call
Chaining Safe-Calls
bob?.department?.head?.name // chain returns null if any property is null
Elvis Operator
val l = b?.length ?:-1// if b is null, return the default value -1// equval to:val l:Int=if (b !=null) b.length else-1
Not Null Assertion Operator
val l = b!!.length // throws a NullPointerException, if b is null
Collections
Immutable list
var programmingLanguages =listOf("C#", "Java", "Kotlin", "Ruby")
Mutable List
var fruits =mutableListOf("Orange", "Apple", "Banana", "Mango")
Access List
var cars =listOf("BMW", "Ferrari", "Volvo", "Tesla")
println(cars[2]) // Prints: Volvo
var seas =listOf("Black Sea", "Caribbean Sea", "North Sea")
println(seas. contains("North Sea")) // Prints: true// The contains() function performs a read operation on any list and determines if the element exists
seas.add("Baltic Sea") // Error: cannot write to immutable list// The add() function can only be called on mutable lists, so the code above throws an error
Immutable Sets
var primaryColors =setOf("Red", "Blue", "Yellow")
Mutable Sets
var womenInTech =mutableSetOf("Ada Lovelace", "Grace Hopper", "Radia Perlman", "Sister Mary Kenneth Keller")
Access Collection Elements {.row-span-2}
var companies =setOf("Facebook", "Apple", "Netflix", "Google")
println(companies.elementAt(3))
// Prints: Googleprintln(companies.elementAt(4))
// Returns and Errorprintln(companies.elementAtOrNull(4))
// Prints: null
Immutable Map
var averageTemp =mapOf("winter" to 35, "spring" to 60, "summer" to 85, "fall" to 55)
Mutable Mapping
var europeanDomains =mutableMapOf("Germany" to "de", "Slovakia" to "sk", "Hungary" to "hu", "Norway" to "no")
Retrieve map keys and values
var oscarWinners =mutableMapOf("Parasite" to "Bong Joon-ho", "Green Book" to "Jim Burke", "The Shape Of Water" to "Guillermo del Toro")
println(oscarWinners.keys)
// Prints: [Parasite, Green Book, The Shape Of Water]println(oscarWinners.values)
// Prints: [Bong Joon-ho, Jim Burke, Guillermo del Toro]println(oscarWinners["Parasite"])
// Prints: Bong Joon-ho
Add and remove map entries
var worldCapitals =mutableMapOf("United States" to "Washington D.C.", "Germany" to "Berlin", "Mexico" to "Mexico City", "France" to "Paris")
worldCapitals.put("Brazil", "Brasilia")
println(worldCapitals)
// Prints: {United States=Washington D.C., Germany=Berlin, Mexico=Mexico City, France=Paris, Brazil=Brasilia}
worldCapitals.remove("Germany")
println(worldCapitals)
// Prints: {United States=Washington D.C., Mexico=Mexico City, France=Paris, Brazil=Brasilia}
funfavoriteLanguage(name:String, language:String = "Kotlin") {
println("Hello, $name. Your favorite programming language is $language")
}
funmain() {
favoriteLanguage("Manon")
//Prints: Hello, Manon. Your favorite programming language is Kotlin
favoriteLanguage("Lee", "Java")
//Prints: Hello, Lee. Your favorite programming language is Java
}
Named Parameters
funfindMyAge(currentYear:Int, birthYear:Int) {
var myAge = currentYear -birthYear
println("I am $myAge years old.")
}
funmain() {
findMyAge(currentYear =2020, birthYear =1995)
//Prints: I am 25 years old.
findMyAge(birthYear =1920, currentYear =2020)
//Prints: I am 100 years old.
}
Return Statement
//Return type is declared outside the parenthesesfungetArea(length:Int, width:Int): Int {
var area = length *width
//return statementreturn area
}
funmain() {
var myArea = getArea(10, 8)
println("The area is $myArea.")
//Prints: The area is 80.
}
Single expression function
fun fullName(firstName: String, lastName: String) = "$firstName $lastName"
fun main() {
println(fullName("Ariana", "Ortega"))
//Prints: Ariana Ortega
println(fullName("Kai", "Gittens"))
//Prints: Kai Gittens
}
Function Literals
fun main() {
//Anonymous Function:
var getProduct = fun(num1: Int, num2: Int): Int {
return num1 *num2
}
println(getProduct(8, 3))
//Prints: 24
//Lambda Expression
var getDifference = { num1: Int, num2: Int -> num1 -num2 }
println(getDifference(10, 3))
//Prints: 7
}
Class
Class Example
//class with properties containing default valuesclassStudent {
var name ="Lucia"var semester ="Fall"var gpa =3.95
}
//shorthand syntax without class bodyclassStudent
Class Instance
// ClassclassStudent {
var name ="Lucia"var semester ="Fall"var gpa =3.95
}
funmain() {
var student =Student()
// Instanceprintln(student.name)
// Prints: Luciaprintln(student.semester)
// Prints: Fallprintln(student.gpa)
// Prints: 3.95
}
classStudent(valname:String, valgpa:Double, valsemester:String, valestimatedGraduationYear:Int) {
init {
println("$name has ${estimatedGraduationYear -2020} years left in college.")
}
}
funmain() {
var student =Student("Lucia", 3.95, "Fall", 2022)
//Prints: Lucia has 2 years left in college.
}
Member Function {.col-span-2}
classStudent(valname:String, valgpa:Double, valsemester:String, valestimatedGraduationYear:Int) {
init {
println("$name has ${estimatedGraduationYear -2020} years left in college.")
}
//member functionfuncalculateLetterGrade(): String {
returnwhen {
gpa >=3.0->"A"
gpa >=2.7->"B"
gpa >=1.7->"C"
gpa >=1.0->"D"else->"E"
}
}
}
//When the instance is created and the function is called, the when expression will be executed and return the letter gradefunmain() {
var student =Student("Lucia", 3.95, "Fall", 2022)
//Prints: Lucia has 2 years left in college.println("${student.name}'s letter grade is ${student.calculateLetterGrade()}.")
//Prints: Lucia's letter grade is A.
}