SlideShare a Scribd company logo
Kotlin
In
Action
Presented by Mehdi Hasanzadeh
Kotlin In Action
Summary Kotlin in Action guides experienced
Java developers from the language basics of
Kotlin all the way through building applications to
run on the JVM and Android devices.
Originally published: December 28, 2016
Authors: Dmitry Jemerov, Svetlana Isakova
Kotlin In Action - M.Hasanzadeh
2. Kotlin Basics
This chapter covers
➔ Declaring functions, variables,
classes, enums, and properties
➔ Control structures in Kotlin
➔ Smart casts
➔ Throwing and handling
exceptions
Hello World
1. fun keyword
2. The parameter type is written after
its name
3. The function can be declared at
the top level of a file
4. Arrays are just classes
5. Println -> Kotlin standard library
6. You can omit the semicolon
Kotlin In Action - M.Hasanzadeh
Functions
The function declaration starts with the fun keyword,
followed by the function name: max, in this case. It’s
followed by the parameter list in parentheses. The return
type comes after the parameter list, separated from it by
a colon.
Ternary operator in Java: (a > b) ? a : b
Kotlin In Action - M.Hasanzadeh
Statements & Expressions
● The difference between a statement and an expression is that an
expression has a value
● In Java, all control structures are statements. In Kotlin, most control
structures, except for the loops (for, do, and do/while) are expressions
● assignments are expressions in Java and become statements in Kotlin.
This helps avoid confusion between comparisons and assignments, which
is a common source of mistakes.
Kotlin In Action - M.Hasanzadeh
Block vs. Expression Body
fun max(a: Int, b: Int): Int = if (a > b) a else b
fun max(a: Int, b: Int) = if (a > b) a else b
Kotlin In Action - M.Hasanzadeh
INTELLIJ IDEA TIP
IntelliJ IDEA provides
intention actions to convert
between the two styles of
functions: “Convert to
expression body” and
“Convert to block body.”
for expression-body functions, the compiler can analyze the
expression used as the body of the function and use its type as
the function return type, even when it’s not spelled out explicitly.
This type of analysis is usually called type inference
Variables
val question = "Is Soroush really a Messenger??"
val answer = 42
Kotlin In Action - M.Hasanzadeh
● If a variable doesn’t have an initializer, you need to specify its type explicitly:
omits the type
declarations
val answer: Int
answer = 42
Mutable & Immutable VARIABLES
● val (from value)—Immutable reference. final variable in Java
● var (from variable)—Mutable reference
● you should declare all variables in Kotlin with the val keyword. Change it to
var only if necessary. Using immutable references, immutable objects, and
functions without side effects makes your code closer to the functional
style.
Kotlin In Action - M.Hasanzadeh
M & IM VARIABLES (Cont.)
● val reference is itself immutable and can’t be changed, the object that it
points to may be mutable.
Kotlin In Action - M.Hasanzadeh
val languages = arrayListOf("Java")
languages.add("Kotlin")
● Error: type mismatch
var answer = 42
answer = "no answer"
String Templates
● $ : Like many scripting languages
● println("$x")
● Nest double quotes within double
quotes
Kotlin In Action - M.Hasanzadeh
Tip
The compiled code
creates a StringBuilder
and appends the
constant parts and
variable values to it
Classes & Properties
/* Java */
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Kotlin In Action - M.Hasanzadeh
class Person(val name: String)
● Kotlin, public is the default visibility
● val is read-only, whereas a var property
is mutable and can be changed
Read-only property: generates
a field and a trivial gette
Writable property: a field,
a getter, and a setter
Kotlin In Action - M.Hasanzadeh
Kotlin In Action - M.Hasanzadeh
Tip
You can also use the Kotlin property syntax for classes defined in Java.
Getters in a Java class can be accessed as val properties from Kotlin, and
getter/setter pairs can be accessed as var properties. For example, if a Java
class defines methods called getName and setName, you can access it as a
property called name. If it defines isMarried and setMarried methods, the name
of the corresponding Kotlin property will be isMarried.
Custom
Accessors ● get() = height == width
Kotlin In Action - M.Hasanzadeh
Question?
You might ask whether
it’s better to declare a
function without
parameters or a property
with a custom getter
Kotlin In Action - M.Hasanzadeh
Answer
Both options are similar: There is no difference in implementation or
performance; they only differ in readability. Generally, if you describe the
characteristic (the property) of a class, you should declare it as a property.
Kotlin In Action - M.Hasanzadeh
Directories & Packages
● Kotlin doesn’t make a distinction between importing classes and functions,
and it allows you to import any kind of declaration using the import
keyword. You can import the top-level function by name.
import geometry.shapes.createRandomRectangle
● In Kotlin, you can put multiple classes in the same file and choose any
name for that file. Kotlin also doesn’t impose any restrictions on the layout
of source files on disk;
enums and “when
● In Kotlin, enum is a so-called soft
keyword
● Enum constants use the same
constructor and property declaration
syntax as you saw earlier for regular
classes. When you declare each enum
constant, you need to provide the
property values for that constant
● only place in the Kotlin syntax where
you’re required to use semicolons
Kotlin In Action - M.Hasanzadeh
Using “when” to
deal with enum
classes
● Like if, when is an expression that
returns a value
● a missing break is often a cause for
bugs in Java code
Kotlin In Action - M.Hasanzadeh
Using “when” with
arbitrary objects
● Unlike switch, which requires you to
use constants (enum constants,
strings, or number literals) as branch
conditions, when allows any objects.
● The Kotlin standard library contains a
function setOf that creates a Set
containing the objects specified as its
arguments
● it means either c1 is RED and c2 is
YELLOW, or vice versa
Kotlin In Action - M.Hasanzadeh
Using “when” without
an argument ● Normally this isn’t an issue, but if the
function is called often, it’s worth
rewriting the code in a different way to
avoid creating garbage. You can do it
by using the when expression without
an argument. The code is less
readable, but that’s the price you often
have to pay to achieve better
performance
● If no argument is supplied for the
when expression, the branch condition
is any Boolean expression.
Kotlin In Action - M.Hasanzadeh
Smart Casts:
combining type checks and casts
● First block : This explicit cast to Num
is redundant.
● Second block : The variable e is
smart-cast.
● In Kotlin, the compiler does this job for
you. If you check the variable for a
certain type, you don’t need to cast it
afterward; you can use it as having the
type you checked for
Kotlin In Action - M.Hasanzadeh
Smart Casts (Cont.)
Kotlin In Action - M.Hasanzadeh
INTELLIJ IDEA TIP
The IDE highlights smart
casts with a background
color.
When you’re using a smart cast with a property of a class, as
in this example, the property has to be a val and it can’t have a
custom accessor. Otherwise, it would not be possible to verify that
every access to the property would return the same value. An
explicit cast to the specific type is expressed via the as keyword
val n = e as Num
Refactoring:
replacing “if” with “when”
● The when expression isn’t restricted to
checking values for equality, which is
what you saw earlier check the type of
the when
Kotlin In Action - M.Hasanzadeh
Blocks as branches of
“if” and “when”
● the last expression in the block is the
result
● The rule “the last expression in a block
is the result” holds in all cases where a
block can be used and a result is
expected
● this rule doesn’t hold for regular
functions
Kotlin In Action - M.Hasanzadeh
Iterating over things:
“while” and “for” loops
Kotlin In Action - M.Hasanzadeh
● Kotlin has while and do-while loops, and their syntax doesn’t
differ from the corresponding loops in Java
for <item> in <elements>
Iterating over numbers:
ranges and progressions
Kotlin In Action - M.Hasanzadeh
● Note that ranges in Kotlin are closed or inclusive
● The most basic thing you can do with integer ranges is loop over all the values. If you
can iterate over all the values in a range, such a range is called a progression
● The step can also be negative
● Unltil syntax:
val oneToTen = 1..10 .. operator
for (x in 0 until size) ~~ for (x in 0..size-1)
Iterating over maps
● Iterates over a map, assigning the
map key and value to two variables
● The rule “the last expression in a block
is the result” holds in all cases where a
block can be used and a result is
expected
● this rule doesn’t hold for regular
functions
Kotlin In Action - M.Hasanzadeh
Using “in” to check
collection and range
membership
● Iterates over a map, assigning the
map key and value to two variables
● You use the in operator to check
whether a value is in a range, or its
opposite, !in, to check whether a value
isn’t in a range
● The in and !in operators also work in
when expressions.
● If you have any class that supports
comparing instances (by implementing
the java.lang.Comparable interface),
you can create ranges of objects of
that type
Kotlin In Action - M.Hasanzadeh
Exceptions in Kotlin
Kotlin In Action - M.Hasanzadeh
● in Kotlin the throw construct is an expression and can be used as a part of other
expressions
variable isn’t initialized
val percentage =
if (number in 0..100)
Number
Else
throw IllegalArgumentException(
"A percentage value must be between 0 and 100: $number")
“try”, “catch”, and “finally”
Kotlin In Action - M.Hasanzadeh
● The biggest difference from Java is that the throws clause isn’t present in the code: if
you wrote this function in Java, you’d explicitly write throws IOException after the
function declaration
● What about Java 7’s
Try-with-resources?
Kotlin doesn’t have any
special syntax for this;
THE
END

More Related Content

PPTX
Exploring Kotlin language basics for Android App development
PPT
Virtual Function
PPT
Constructors and destructors in C++ part 2
PPSX
Object oriented concepts & programming (2620003)
PPTX
Polymorphism
PPS
Dacj 1-3 a
PPTX
Kotlin Code style guidelines
PDF
Functional programming in scala
Exploring Kotlin language basics for Android App development
Virtual Function
Constructors and destructors in C++ part 2
Object oriented concepts & programming (2620003)
Polymorphism
Dacj 1-3 a
Kotlin Code style guidelines
Functional programming in scala

What's hot (20)

PDF
Java essentials for hadoop
PPTX
Introduction to Kotlin for Android developers
PDF
(3) c sharp introduction_basics_part_ii
DOC
Interface Vs Abstact
PPTX
Object oriented java script
PPT
ParaSail
PDF
Xtext Webinar
PDF
Chapter 7 recursion handouts with notes
PDF
Functional Programming in Java
PDF
Why should a Java programmer shifts towards Functional Programming Paradigm
PDF
2 BytesC++ course_2014_c6_ constructors and other tools
PDF
Value Objects
PDF
PDF
Functional programming with Java 8
PPTX
Introduction to functional programming with java 8
PPTX
Constructor in java
PDF
Esta charla es una monada - Introducción a FP en JavaScript con Ramda
PPTX
Virtual function and abstract class
PPTX
Java basics and java variables
PPTX
C# 6.0 and 7.0 new features
Java essentials for hadoop
Introduction to Kotlin for Android developers
(3) c sharp introduction_basics_part_ii
Interface Vs Abstact
Object oriented java script
ParaSail
Xtext Webinar
Chapter 7 recursion handouts with notes
Functional Programming in Java
Why should a Java programmer shifts towards Functional Programming Paradigm
2 BytesC++ course_2014_c6_ constructors and other tools
Value Objects
Functional programming with Java 8
Introduction to functional programming with java 8
Constructor in java
Esta charla es una monada - Introducción a FP en JavaScript con Ramda
Virtual function and abstract class
Java basics and java variables
C# 6.0 and 7.0 new features
Ad

Similar to Kotlin in action (20)

PDF
9054799 dzone-refcard267-kotlin
PDF
Basics of kotlin ASJ
PDF
Introduction to kotlin for Java Developer
PPTX
Day 2 Compose Camp.pptx
PPTX
Introduction to Scala
PDF
Introduction to Kotlin - Android KTX
PPTX
Introduction to Koltin for Android Part I
PDF
From Java to Kotlin
PPTX
Intro to Scala
PDF
Review of c_sharp2_features_part_iii
PDF
Important JavaScript Concepts Every Developer Must Know
PDF
Swift Tutorial Part 2. The complete guide for Swift programming language
PPTX
Design patterns with Kotlin
PPTX
How to replace switch with when in kotlin
PDF
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
PPTX
Object oriented programming in java
PPTX
Java For Automation
PPTX
‫Object Oriented Programming_Lecture 3
PPTX
Unit 1 part for information technology 1.pptx
PDF
java script functions, classes
9054799 dzone-refcard267-kotlin
Basics of kotlin ASJ
Introduction to kotlin for Java Developer
Day 2 Compose Camp.pptx
Introduction to Scala
Introduction to Kotlin - Android KTX
Introduction to Koltin for Android Part I
From Java to Kotlin
Intro to Scala
Review of c_sharp2_features_part_iii
Important JavaScript Concepts Every Developer Must Know
Swift Tutorial Part 2. The complete guide for Swift programming language
Design patterns with Kotlin
How to replace switch with when in kotlin
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Object oriented programming in java
Java For Automation
‫Object Oriented Programming_Lecture 3
Unit 1 part for information technology 1.pptx
java script functions, classes
Ad

Recently uploaded (20)

PDF
medical staffing services at VALiNTRY
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
top salesforce developer skills in 2025.pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Designing Intelligence for the Shop Floor.pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
System and Network Administraation Chapter 3
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Nekopoi APK 2025 free lastest update
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
medical staffing services at VALiNTRY
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
top salesforce developer skills in 2025.pdf
PTS Company Brochure 2025 (1).pdf.......
Digital Systems & Binary Numbers (comprehensive )
2025 Textile ERP Trends: SAP, Odoo & Oracle
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Designing Intelligence for the Shop Floor.pdf
How to Migrate SBCGlobal Email to Yahoo Easily
Computer Software and OS of computer science of grade 11.pptx
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
System and Network Administraation Chapter 3
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Odoo Companies in India – Driving Business Transformation.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Nekopoi APK 2025 free lastest update
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf

Kotlin in action

  • 2. Kotlin In Action Summary Kotlin in Action guides experienced Java developers from the language basics of Kotlin all the way through building applications to run on the JVM and Android devices. Originally published: December 28, 2016 Authors: Dmitry Jemerov, Svetlana Isakova Kotlin In Action - M.Hasanzadeh
  • 3. 2. Kotlin Basics This chapter covers ➔ Declaring functions, variables, classes, enums, and properties ➔ Control structures in Kotlin ➔ Smart casts ➔ Throwing and handling exceptions
  • 4. Hello World 1. fun keyword 2. The parameter type is written after its name 3. The function can be declared at the top level of a file 4. Arrays are just classes 5. Println -> Kotlin standard library 6. You can omit the semicolon Kotlin In Action - M.Hasanzadeh
  • 5. Functions The function declaration starts with the fun keyword, followed by the function name: max, in this case. It’s followed by the parameter list in parentheses. The return type comes after the parameter list, separated from it by a colon. Ternary operator in Java: (a > b) ? a : b Kotlin In Action - M.Hasanzadeh
  • 6. Statements & Expressions ● The difference between a statement and an expression is that an expression has a value ● In Java, all control structures are statements. In Kotlin, most control structures, except for the loops (for, do, and do/while) are expressions ● assignments are expressions in Java and become statements in Kotlin. This helps avoid confusion between comparisons and assignments, which is a common source of mistakes. Kotlin In Action - M.Hasanzadeh
  • 7. Block vs. Expression Body fun max(a: Int, b: Int): Int = if (a > b) a else b fun max(a: Int, b: Int) = if (a > b) a else b Kotlin In Action - M.Hasanzadeh INTELLIJ IDEA TIP IntelliJ IDEA provides intention actions to convert between the two styles of functions: “Convert to expression body” and “Convert to block body.” for expression-body functions, the compiler can analyze the expression used as the body of the function and use its type as the function return type, even when it’s not spelled out explicitly. This type of analysis is usually called type inference
  • 8. Variables val question = "Is Soroush really a Messenger??" val answer = 42 Kotlin In Action - M.Hasanzadeh ● If a variable doesn’t have an initializer, you need to specify its type explicitly: omits the type declarations val answer: Int answer = 42
  • 9. Mutable & Immutable VARIABLES ● val (from value)—Immutable reference. final variable in Java ● var (from variable)—Mutable reference ● you should declare all variables in Kotlin with the val keyword. Change it to var only if necessary. Using immutable references, immutable objects, and functions without side effects makes your code closer to the functional style. Kotlin In Action - M.Hasanzadeh
  • 10. M & IM VARIABLES (Cont.) ● val reference is itself immutable and can’t be changed, the object that it points to may be mutable. Kotlin In Action - M.Hasanzadeh val languages = arrayListOf("Java") languages.add("Kotlin") ● Error: type mismatch var answer = 42 answer = "no answer"
  • 11. String Templates ● $ : Like many scripting languages ● println("$x") ● Nest double quotes within double quotes Kotlin In Action - M.Hasanzadeh Tip The compiled code creates a StringBuilder and appends the constant parts and variable values to it
  • 12. Classes & Properties /* Java */ public class Person { private final String name; public Person(String name) { this.name = name; } public String getName() { return name; } } Kotlin In Action - M.Hasanzadeh class Person(val name: String) ● Kotlin, public is the default visibility ● val is read-only, whereas a var property is mutable and can be changed
  • 13. Read-only property: generates a field and a trivial gette Writable property: a field, a getter, and a setter Kotlin In Action - M.Hasanzadeh
  • 14. Kotlin In Action - M.Hasanzadeh Tip You can also use the Kotlin property syntax for classes defined in Java. Getters in a Java class can be accessed as val properties from Kotlin, and getter/setter pairs can be accessed as var properties. For example, if a Java class defines methods called getName and setName, you can access it as a property called name. If it defines isMarried and setMarried methods, the name of the corresponding Kotlin property will be isMarried.
  • 15. Custom Accessors ● get() = height == width Kotlin In Action - M.Hasanzadeh Question? You might ask whether it’s better to declare a function without parameters or a property with a custom getter
  • 16. Kotlin In Action - M.Hasanzadeh Answer Both options are similar: There is no difference in implementation or performance; they only differ in readability. Generally, if you describe the characteristic (the property) of a class, you should declare it as a property.
  • 17. Kotlin In Action - M.Hasanzadeh Directories & Packages ● Kotlin doesn’t make a distinction between importing classes and functions, and it allows you to import any kind of declaration using the import keyword. You can import the top-level function by name. import geometry.shapes.createRandomRectangle ● In Kotlin, you can put multiple classes in the same file and choose any name for that file. Kotlin also doesn’t impose any restrictions on the layout of source files on disk;
  • 18. enums and “when ● In Kotlin, enum is a so-called soft keyword ● Enum constants use the same constructor and property declaration syntax as you saw earlier for regular classes. When you declare each enum constant, you need to provide the property values for that constant ● only place in the Kotlin syntax where you’re required to use semicolons Kotlin In Action - M.Hasanzadeh
  • 19. Using “when” to deal with enum classes ● Like if, when is an expression that returns a value ● a missing break is often a cause for bugs in Java code Kotlin In Action - M.Hasanzadeh
  • 20. Using “when” with arbitrary objects ● Unlike switch, which requires you to use constants (enum constants, strings, or number literals) as branch conditions, when allows any objects. ● The Kotlin standard library contains a function setOf that creates a Set containing the objects specified as its arguments ● it means either c1 is RED and c2 is YELLOW, or vice versa Kotlin In Action - M.Hasanzadeh
  • 21. Using “when” without an argument ● Normally this isn’t an issue, but if the function is called often, it’s worth rewriting the code in a different way to avoid creating garbage. You can do it by using the when expression without an argument. The code is less readable, but that’s the price you often have to pay to achieve better performance ● If no argument is supplied for the when expression, the branch condition is any Boolean expression. Kotlin In Action - M.Hasanzadeh
  • 22. Smart Casts: combining type checks and casts ● First block : This explicit cast to Num is redundant. ● Second block : The variable e is smart-cast. ● In Kotlin, the compiler does this job for you. If you check the variable for a certain type, you don’t need to cast it afterward; you can use it as having the type you checked for Kotlin In Action - M.Hasanzadeh
  • 23. Smart Casts (Cont.) Kotlin In Action - M.Hasanzadeh INTELLIJ IDEA TIP The IDE highlights smart casts with a background color. When you’re using a smart cast with a property of a class, as in this example, the property has to be a val and it can’t have a custom accessor. Otherwise, it would not be possible to verify that every access to the property would return the same value. An explicit cast to the specific type is expressed via the as keyword val n = e as Num
  • 24. Refactoring: replacing “if” with “when” ● The when expression isn’t restricted to checking values for equality, which is what you saw earlier check the type of the when Kotlin In Action - M.Hasanzadeh
  • 25. Blocks as branches of “if” and “when” ● the last expression in the block is the result ● The rule “the last expression in a block is the result” holds in all cases where a block can be used and a result is expected ● this rule doesn’t hold for regular functions Kotlin In Action - M.Hasanzadeh
  • 26. Iterating over things: “while” and “for” loops Kotlin In Action - M.Hasanzadeh ● Kotlin has while and do-while loops, and their syntax doesn’t differ from the corresponding loops in Java for <item> in <elements>
  • 27. Iterating over numbers: ranges and progressions Kotlin In Action - M.Hasanzadeh ● Note that ranges in Kotlin are closed or inclusive ● The most basic thing you can do with integer ranges is loop over all the values. If you can iterate over all the values in a range, such a range is called a progression ● The step can also be negative ● Unltil syntax: val oneToTen = 1..10 .. operator for (x in 0 until size) ~~ for (x in 0..size-1)
  • 28. Iterating over maps ● Iterates over a map, assigning the map key and value to two variables ● The rule “the last expression in a block is the result” holds in all cases where a block can be used and a result is expected ● this rule doesn’t hold for regular functions Kotlin In Action - M.Hasanzadeh
  • 29. Using “in” to check collection and range membership ● Iterates over a map, assigning the map key and value to two variables ● You use the in operator to check whether a value is in a range, or its opposite, !in, to check whether a value isn’t in a range ● The in and !in operators also work in when expressions. ● If you have any class that supports comparing instances (by implementing the java.lang.Comparable interface), you can create ranges of objects of that type Kotlin In Action - M.Hasanzadeh
  • 30. Exceptions in Kotlin Kotlin In Action - M.Hasanzadeh ● in Kotlin the throw construct is an expression and can be used as a part of other expressions variable isn’t initialized val percentage = if (number in 0..100) Number Else throw IllegalArgumentException( "A percentage value must be between 0 and 100: $number")
  • 31. “try”, “catch”, and “finally” Kotlin In Action - M.Hasanzadeh ● The biggest difference from Java is that the throws clause isn’t present in the code: if you wrote this function in Java, you’d explicitly write throws IOException after the function declaration ● What about Java 7’s Try-with-resources? Kotlin doesn’t have any special syntax for this;