Kotlin Tutorial
A concise, null safe language for Android and servers.
Getting started3 lessons
Basics25 lessons
- 4Kotlin Variablesval creates a read only variable and var creates one you can change.
- 5Kotlin Data TypesNumbers are Int, Long, Double and Float.
- 6Kotlin StringsStrings use $name or ${expression} templates.
- 7Kotlin Null SafetyTypes are non null by default.
- 8Kotlin Input and Outputprintln prints with a newline and print does not.
- 9Kotlin CommentsUse // for one line and /* */ for several.
- 10Kotlin BooleansBoolean has two values, true and false.
- 11Kotlin Constantsconst val declares a compile time constant at top level or in an object.
- 12Type Checks and Smart Castsis tests a type, and after the test Kotlin smart casts the value automatically.
- 13Kotlin Break and Continuebreak exits a loop and continue skips to the next round.
- 14val and varval is read only and var can change.
- 15Basic TypesInt, Long, Double, Float, Boolean, Char and String.
- 16Null SafetyTypes cannot hold null unless you add ?.
- 17String Templates$name and ${expression} insert values into strings.
- 18Type ConversionKotlin never converts numbers implicitly.
- 19OperatorsArithmetic, comparison, logical and range operators.
- 20Equality: == and ===== compares values with equals and === compares references.
- 21Reading Inputreadln() reads a line and readlnOrNull() returns null at the end of input.
- 22Math Functionskotlin.math has abs, max, min, pow, sqrt, round, floor, ceil and PI.
- 23Random Numberskotlin.random.Random gives ints, doubles and booleans.
- 24The main FunctionEvery program starts in main.
- 25Comments and KDoc// starts a line comment and /* */ a block.
- 26const and lateinitconst val is a compile time constant.
- 27Char and BooleanChar holds one character and supports arithmetic.
- 28Any, is and asAny is the root type.
Operators2 lessons
Control flow9 lessons
- 31Kotlin If as an Expressionif is an expression, so it returns a value and replaces the ternary operator.
- 32Kotlin Whenwhen replaces switch and is much more powerful.
- 33Kotlin Loopsfor iterates over ranges and collections, while and do while repeat on a condition.
- 34if as an Expressionif returns a value, so there is no ternary operator.
- 35whenwhen replaces switch.
- 36for Loopsfor walks any iterable.
- 37while and do whilewhile checks first and do while runs at least once.
- 38break, continue and Labelsbreak leaves a loop, continue skips a round and labels target outer loops.
- 39Ranges and ProgressionsA range such as 1..5 is a sequence you can test, loop over and convert.
Collections18 lessons
- 40Kotlin ArraysarrayOf creates an array of fixed size.
- 41Kotlin ListslistOf creates an immutable list and mutableListOf one you can change.
- 42Kotlin Sets and MapsA set holds unique values and a map holds key value pairs.
- 43Kotlin Collection Functionsmap, filter, reduce, sum, any, all, groupBy and sortedBy transform collections in a functi.
- 44ListslistOf is read only and mutableListOf can change.
- 45Collection Operationsmap, filter, reduce, sortedBy, groupBy, any, all, sum and take are the daily tools.
- 46SetssetOf holds unique values.
- 47MapsmapOf pairs keys with values using to.
- 48SequencesSequences are lazy.
- 49ArraysarrayOf and intArrayOf create fixed size arrays.
- 50DestructuringPull values from pairs, data classes and maps into variables.
- 51String OperationsCommon string functions: substring, split, replace, trim, startsWith, contains and format.
- 52groupBy, associate and partitiongroupBy buckets items, associateBy builds a map and partition splits in two.
- 53fold and reducereduce combines items with the first as the start.
- 54zip, flatten and windowedzip pairs two lists, flatten merges nested lists and windowed makes sliding windows.
- 55distinct, count and minOfdistinct removes duplicates, count counts matches and minBy and maxBy find extremes.
- 56StringBuilder and buildStringUse StringBuilder or buildString for many appends.
- 57Pairs and TriplesPair and Triple hold two or three values.
Functions10 lessons
- 58Kotlin FunctionsDeclare with fun.
- 59Default and Named ArgumentsParameters can have defaults, and callers can name arguments in any order.
- 60Lambdas and Higher Order FunctionsA lambda is a function written in braces.
- 61Functionsfun declares a function.
- 62Default and Named ArgumentsGive parameters defaults and name them when calling.
- 63varargvararg accepts any number of arguments as an array.
- 64Lambdas and Higher Order FunctionsA lambda is { params -> body }.
- 65Extension FunctionsAdd functions to existing types without inheritance.
- 66Scope Functionslet, run, apply, also and with run code on an object.
- 67Recursion and tailrecA function may call itself.
Object oriented Kotlin21 lessons
- 68Kotlin Classes and ObjectsA class has properties and functions.
- 69Kotlin InheritanceClasses are final by default, so mark a base class open.
- 70Kotlin Data ClassesA data class automatically gets equals, hashCode, toString and copy.
- 71Kotlin Interfaces and Abstract ClassesAn interface lists members and may give default implementations.
- 72Object and Companion Objectobject declares a singleton.
- 73Enums and Sealed Classesenum class defines constants.
- 74Properties, Getters and SettersProperties can have custom get and set blocks.
- 75Visibility Modifierspublic is the default.
- 76Operator OverloadingMark a function operator to give + - * and others meaning for your own types, for example .
- 77Destructuring and TypealiasDestructuring unpacks a data class or pair into variables.
- 78ClassesA class has a primary constructor, properties and methods.
- 79Data Classesdata classes generate equals, hashCode, toString, copy and componentN.
- 80Properties, Getters and SettersProperties have automatic getters and setters.
- 81InheritanceClasses are final by default.
- 82InterfacesInterfaces can contain default method bodies.
- 83abstract and sealed Classesabstract classes cannot be created.
- 84object and companion objectobject makes a singleton.
- 85Enum Classesenum class lists constants that can have properties and methods.
- 86GenericsType parameters make classes and functions work with many types.
- 87Delegation and lazyby lazy runs code once on first use.
- 88Operator Overloadingoperator fun plus, minus, get and compareTo make types work with operators.
Errors and files11 lessons
- 89Kotlin Exceptionstry, catch and finally handle errors.
- 90Kotlin Filesjava.io.File with Kotlin extensions reads and writes: readText, writeText, appendText, rea.
- 91try, catch and finallytry is an expression.
- 92throw and Custom Exceptionsthrow raises an exception.
- 93FilesreadText, writeText and forEachLine handle files.
- 94Coroutines IntroductionCoroutines run asynchronous work in a sequential style.
- 95Safe Calls and let?.let runs a block only if the value is not null.
- 96Smart CastsAfter an is check the compiler treats the value as that type.
- 97Practice: Word FrequencySplit, group and sort.
- 98Practice: FizzBuzzCombine a range with when.
- 99Practice: Bank AccountCombine a class, validation and exceptions.
Advanced KotlinPremium7 lessons
- 100Extension FunctionsAdd functions to existing types without inheriting from them.
- 101Scope Functionslet, run, with, apply and also run a block on an object.
- 102Kotlin GenericsGenerics make code work with many types safely.
- 103CoroutinesCoroutines run asynchronous work without blocking threads.
- 104Kotlin FlowA Flow emits values over time and is the coroutine version of sequences or streams.
- 105Delegation and Lazyby delegates behaviour.
- 106Inline Functions and DSLsinline copies a function body into call sites to avoid lambda overhead.
Kotlin in practicePremium6 lessons
- 107Kotlin for AndroidAndroid apps use Kotlin with Jetpack Compose for the UI.
- 108Ktor Web ServerKtor is a Kotlin framework for servers and clients.
- 109Testing KotlinUse JUnit with kotlin.test.
- 110Gradle and DependenciesGradle builds Kotlin projects.
- 111Java InteroperabilityKotlin and Java mix in one project.
- 112Kotlin Best PracticesPrefer val, immutable collections and data classes.