Kotlin Jump Start Online Free Meetup (June 4th, 2024)

lifemichael 32 views 93 slides Jun 04, 2024
Slide 1
Slide 1 of 93
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93

About This Presentation

These are the slides that I used when delivering the Kotlin Jump Start online meetup on June 4th, 2024.

premium professional training for software developers
https://lifemichael.com

synchronous online course for learning Kotlin
https://lifemichael.com/courses/kotlin

professional group for Kotlin...


Slide Content

Kotlin Jump Start
Haim Michael
June 4
th
, 2024
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
life

m
ic
h
a
e
l

09/10/08 © 2024 Haim Michael All Rights Reserved 2
Introduction

09/10/08 © 2024 Haim Michael All Rights Reserved 3
What is Kotlin?
Kotlin is a relatively new programming language
developed by JetBrains.
Kotlin for Multiplatform
Kotlin for Server Side
Kotlin for Android
Kotlin Native
Kotlin Wasm
Kotlin for JavaScript
Kotlin for Data Analysts

09/10/08 © 2024 Haim Michael All Rights Reserved 4
Kotlin Popularity

09/10/08 © 2024 Haim Michael All Rights Reserved 5
Learning Curve
Kotlin, Swift, and Scala are very similar. Knowing one
of these programming languages it would be relatively
simpler learning the others.
It is highly recommended to know Java before you
start learning Kotlin.
Knowing Java, moving forward with Kotlin might be
simpler comparing with Swift and Scala.

09/10/08 © 2024 Haim Michael All Rights Reserved 6
The IDE
The simplest way to start with Kotlin would be using
the IntelliJ IDE.

09/10/08 © 2024 Haim Michael All Rights Reserved 7
The IDE

09/10/08 © 2024 Haim Michael All Rights Reserved 8
Basics

09/10/08 © 2024 Haim Michael All Rights Reserved 9
The package Statement
As with Java, if we don't specify the package then all
content of the file belongs to the default package. The
default package doesn't have a name.
The package statement should be in the beginning of
the file, and before any other statement.
package com.lifemichael.samples.*
import java.util.*
...

09/10/08 © 2024 Haim Michael All Rights Reserved 10
Defining Functions
We define a new unction using the fun keyword. The
types of each one of the parameters should be
specified to the right of them.
The type of the returned value can be specified to the
right of the function definition.

09/10/08 © 2024 Haim Michael All Rights Reserved 11
Defining Functions
package com.lifemichael.kotlin.samples
fun sum(num1:Int, num2:Int):Int {
return num1+num2
}
fun main(args: Array<String>) {
print(sum(4,5))
}

09/10/08 © 2024 Haim Michael All Rights Reserved 12
Defining Functions
When the function includes one expression only... an
expression that its value should be returned... we can omit
the type of the returned value and we can omit the curly
braces.
When doing so, we should add the equal sign for
specifying the function body.
The compiler will automatically infer the type of the
returned value.

09/10/08 © 2024 Haim Michael All Rights Reserved 13
package com.lifemichael.kotlin.samples
fun sum(num1:Int, num2:Int) = num1+num2
fun main(args: Array<String>) {
print(sum(4,5))
}
Defining Functions

09/10/08 © 2024 Haim Michael All Rights Reserved 14
Defining Functions
When defining a function that doesn't return a
meaningful value we can use the type Unit for
specifying the type of the returned value.
It isn't mandatory to specify the Unit type. We can
omit it.

09/10/08 © 2024 Haim Michael All Rights Reserved 15
Defining Functions
package com.lifemichael.kotlin.samples
fun printWithStars(str:String):Unit {
print("*** "+str+" ***")
}
fun main(args: Array<String>) {
printWithStars("shalom")
}

09/10/08 © 2024 Haim Michael All Rights Reserved 16
Defining Local Variables
When creating local variables in our functions we can
either create assign-once (readonly) local variables or
mutable ones.
We create readonly local variables using the val keyword,
and we create mutable local variables using the var
keyword.
The function parameters are implicitly readonly local
variables.

09/10/08 © 2024 Haim Michael All Rights Reserved 17
Defining Local Variables
package com.lifemichael.kotlin.samples
private fun calc(num1:Int,num2:Int):Int {
var total:Int = num1+num2
return total
}
fun main(args: Array<String>) {
print(calc(4,1))
}

09/10/08 © 2024 Haim Michael All Rights Reserved 18
Comments
As with Java, when writing code in Kotlin we can
either use the C or the C++ notations for comments.
// simple c++ notation for one line of comment
/*
simple c notation for multiple lines of comment
*/

09/10/08 © 2024 Haim Michael All Rights Reserved 19
String Templates
We can easily create new templates using a simple
string. The placeholders should be marked with the $
sign and their names should be the names of specific
variables in our code.

09/10/08 © 2024 Haim Michael All Rights Reserved 20
String Templates
package com.lifemichael.kotlin.samples
private fun calc(num1:Int,num2:Int):Unit {
var total:Int = num1+num2
var text:String = "The sum of $num1 and $num2 is $total"
print(text)
}
fun main(args: Array<String>) {
calc(4,1)
}

09/10/08 © 2024 Haim Michael All Rights Reserved 21
The if Statement
Kotlin supports most of the well known conditional
expressions, including if, if-else, while and
many others.

09/10/08 © 2024 Haim Michael All Rights Reserved 22
The if Statement
fun bigger(num1:Int, num2:Int):Int {
if(num1>num2)
return num1
else
return num2
}
fun main(args: Array<String>) {
val a:Int = 12
val b:Int = 20
println(bigger(a,b))
}

09/10/08 © 2024 Haim Michael All Rights Reserved 23
The if Statement
We can use the if statement as an expression. It can
be an expression its value is the value the function
returns, and it can be an expression its value is
assigned to specific variable.
When assigning the value of if statement (we treat as
an expression) the expression is evaluated.

09/10/08 © 2024 Haim Michael All Rights Reserved 24
The if Statement
fun main(args: Array<String>) {
var a:Int = 12
var b:Int = 20
var temp = if(a>b) a else b
a = 40
println(temp)
}

09/10/08 © 2024 Haim Michael All Rights Reserved 25
Nullable Values
When using a nullable values (e.g. Int?) it means that
the value can be null.

09/10/08 © 2024 Haim Michael All Rights Reserved 26
Nullable Values
fun calc(num1:Double, num2:Double):Double? {
if(num2==0.0)
return null
else
return num1/num2
}
fun main(args: Array<String>) {
println(calc(12.2,7.2))
println(calc(10.4,0.0))
println(calc(5.4,3.6))
}

09/10/08 © 2024 Haim Michael All Rights Reserved 27
Type Checks
We can use the is operator for checking a specific
expression if (or not) its value is a reference for an
object that is of a specific type.

09/10/08 © 2024 Haim Michael All Rights Reserved 28
Type Checks
fun f(ob:Any):Unit {
if(ob is String)
println("ob is string")
}
fun main(args: Array<String>) {
val str1:String = "abc"
if(str1 is Any) {
println("str1 is Any")
}
if(str1 is String) {
println("str1 is String")
}
var str2:String = "abc"
if(str2 is Any) {
println("str is Any")
}
if(str2 is String) {
println("str2 is String")
}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 29
The for Loop
When using the for loop we will usually find
ourselves iterating all elements in a specific array or
collection, as if we were using a foreach loop.

09/10/08 © 2024 Haim Michael All Rights Reserved 30
The for Loop
fun main(args: Array<String>) {
val items = listOf("Paris","Tel-Aviv",
"New-York","Rome")
for(item in items) {
println(item)
}
for(index in items.indices) {
println("item at $index is ${items[index]}")
}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 31
The while Loop
The syntax for using the while loop is as in any other
programming language.

09/10/08 © 2024 Haim Michael All Rights Reserved 32
The while Loop
fun main(args: Array<String>) {
var i:Int = 0
while(i<10) {
println("i=$i")
i++
}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 33
The when Expression
The when expression is kind of a sophisticated switch
case statement.

09/10/08 © 2024 Haim Michael All Rights Reserved 34
The when Expression
fun describe(ob:Any):Unit {
when(ob) {
"Israel" -> println("Israel is a country")
"Mazda" -> println("Mazda is a car")
"Ski" -> println("Ski is a winter sport")
}
}
fun main(args: Array<String>) {
describe("Israel")
describe("Ski")
describe("Mazda")
}

09/10/08 © 2024 Haim Michael All Rights Reserved 35
Ranges
We can easily create a range by placing two dots in
between two numbers.
Once a range was created we can use the in operator
to check whether our number is in the range.
Once a range was created we can use it in a for loop
in order to iterate all integer numbers the range
includes.

09/10/08 © 2024 Haim Michael All Rights Reserved 36
Ranges
fun main(args: Array<String>) {
var num:Int = 12
if (num in 1..12) {
println("in range")
}
for(num in 1..10) {
println("num = $num")
}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 37
Collections
Kotlin provides us with more than a few different types
of collections. We can easily iterate the collection
elements by using the for loop.

09/10/08 © 2024 Haim Michael All Rights Reserved 38
Collections
fun main(args: Array<String>) {
val colors = listOf("Red","Green","Blue","Orange")
for(color in colors) {
println(color)
}

}

09/10/08 © 2024 Haim Michael All Rights Reserved 39
Collections
We can easily check whether a given collection
contains a specific object using the in operator.

09/10/08 © 2024 Haim Michael All Rights Reserved 40
Collections
fun main(args: Array<String>) {
val colors = listOf("Red","Green","Blue","Orange")
when {
"Red" in colors -> println("Red is a great color!")
"Orange" in colors -> println("We can go with Orange")
}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 41
Object Oriented
Unlike many other OOP languages, when creating a
new object in Kotlin we don't use the new keyword.

09/10/08 © 2024 Haim Michael All Rights Reserved 42
Object Oriented
class Rectangle (
var height:Double,
var width:Double) {
fun area():Double = height * width
}
fun main(args: Array<String>) {
var ob:Rectangle = Rectangle(5.0,6.0)
println("area is "+ob.area())
}

09/10/08 © 2024 Haim Michael All Rights Reserved 43
Basic Types

09/10/08 © 2024 Haim Michael All Rights Reserved 44
Introduction
In Kotlin, everything is an object. We can invoke member
functions and access properties on any variable.
Some of the objects might have special internal
representation (e.g. numbers, character and booleans....
they are represented as primitive values at runtime). For
the developer working with these types is just as with
working with object of any other class.

09/10/08 © 2024 Haim Michael All Rights Reserved 45
Numbers
Kotlin provides the following built-in types for representing
numbers:
Double, Float, Long, Int, Short and Byte
Characters are not numbers.
Working with integers, we can either work with decimals
(12,200,98,8 etc.), hexadecimals (0x0F) and binaries
(0b010000111).

09/10/08 © 2024 Haim Michael All Rights Reserved 46
Numbers
Working with floating point numbers, their default type is
Double. If you want the type of be Float you should append
the number with f (123.5f).
When dealing with big numbers we can use underscore to
make the numbers constants more readable (1_000_000).
Adding L to integer numbers will turn them into objects of
the type Long (instead of Int).

09/10/08 © 2024 Haim Michael All Rights Reserved 47
Arrays
The arrays in Kotlin are objects instantiated from the
Array class.
The Array class includes the definition for the size
property and for the get and set functions that turn into
[] through operator overloading.
In order to create an array we should use the library
function arrayOf() and pass over the items values.

09/10/08 © 2024 Haim Michael All Rights Reserved 48
Arrays
fun main(args:Array<String>) {
var numbers:Array<Int> = arrayOf(12,45,32,43,6)
for(number in numbers) {
println(number)
}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 49
Arrays
Using the arrayOfNulls method we can create an array
filled with nulls.

09/10/08 © 2024 Haim Michael All Rights Reserved 50
Arrays
fun main(args:Array<String>) {
var numbers:Array<Int?> = arrayOfNulls<Int?>(3)
for(number in numbers) {
println(number)
}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 51
Arrays
The Array constructor also allows us to create a new
Array object by specifying its size and passing over a
function that will generate the initial values.

09/10/08 © 2024 Haim Michael All Rights Reserved 52
Arrays
fun main(args:Array<String>) {
var numbers:Array<Int> = Array(10,{ i->i*i })
for(number in numbers) {
println(number)
}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 53
Arrays
Kotlin also has specialized classes for representing arrays
of primitive types without the auto boxing overhead:
ByteArray, ShortArray, IntArray etc.
These classes don't extend the Array class. Nevertheless,
they have the same set of methods and properties.
Each one of these classes has a factory function we use
for getting a new object.

09/10/08 © 2024 Haim Michael All Rights Reserved 54
Arrays
fun main(args:Array<String>) {
var numbers:IntArray = intArrayOf(10,2,8,13,40)
for(number in numbers) {
println(number)
}
var temp:Int = numbers[0]+numbers[1]
println("temp=$temp")
}

09/10/08 © 2024 Haim Michael All Rights Reserved 55
Strings
Strings are represented using the type String. Strings
are immutable. Each String object is composed of
characters we can access using the index operation.
We can even iterate a string using a simple for loop
and get separately each one of its characters.

09/10/08 © 2024 Haim Michael All Rights Reserved 56
Strings
fun main(args:Array<String>) {
var str = "Python"
for(tav in str) {
println(tav)
}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 57
Classes

09/10/08 © 2024 Haim Michael All Rights Reserved 58
The class Keyword
As with Java, we define classes in Kotlin using the
class keyword.
class BankAccount
{
...
}

09/10/08 © 2024 Haim Michael All Rights Reserved 59
The class Keyword
If the class doesn't have a body then we can take
away the curly braces.
class BankAccount

09/10/08 © 2024 Haim Michael All Rights Reserved 60
Constructors
The class definition can include the definition of a primary
constructors and one (or more) secondary ones.
The primary constructor definition is part of the class
header.
class Person constructor(name:String)
{
...
}

09/10/08 © 2024 Haim Michael All Rights Reserved 61
Primary Constructor
If the primary constructor doesn't have any visibility
modifier and doesn't have any annotation we can
remove the constructor keyword.
class Person(name:String)
{
...
}

09/10/08 © 2024 Haim Michael All Rights Reserved 62
Primary Constructor
The primary constructor cannot contain any code. We
can place the initialization code within initializer blocks
we create using the init keyword.
class Person(name:String){
init {
...
}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 63
Primary Constructor
We can have more than one initializer block. They will
be executed in the order they appear in the code.
Within the initializer blocks we can use the parameters
of the primary constructor.

09/10/08 © 2024 Haim Michael All Rights Reserved 64
Primary Constructor
The primary constructor parameters can also be used
within properties initializers.
class Student(name: String) {
val nickname = name.toLowerCase();
}

09/10/08 © 2024 Haim Michael All Rights Reserved 65
Primary Constructor
When adding val or var to primary constructor
parameter it will become a property in our class.
class Rectangle (val width: Double, val height: Double)
var rec:Rectangle = Rectangle(3.2,4.0)
fun main(args: Array<String>) {
print(rec.width)
}

09/10/08 © 2024 Haim Michael All Rights Reserved 66
Primary Constructor
If the constructor has annotations or visibility modifiers
then we must use the constructor keyword. The
modifiers will be placed before it.
class Rectangle public constructor(val width: Double)
var rec:Rectangle = Rectangle(3.2,4.0)
fun main(args: Array<String>) {
print(rec.width)
}

09/10/08 © 2024 Haim Michael All Rights Reserved 67
Secondary Constructors
In addition to the primary constructor we can define
secondary constructors. Each secondary constructor
is prefixed with the constructor keyword.
class Person (val name: String) {
constructor(name:String, father:String):this(name) {
father.childrens.add(this)
}
}
Calling the primary constructor means
invoking the initialize blocks.

09/10/08 © 2024 Haim Michael All Rights Reserved 68
The Base Class
In order to specify the supertype, we should place the
super type after a colon in the class header. If the base
class has a primary constructor, the base type must be
initialized right there, using the parameters of the primary
constructor.
class Derived(name:String) : Base(name)

09/10/08 © 2024 Haim Michael All Rights Reserved 69
The Base Class
If the base class doesn't have a primary constructor, then
each secondary constructor in our derived class should
initialize the base type using the super keyword, or to
delegate to another constructor that does it.
If this is the case, each one of the base class secondary
constructors can call a different constructor in the base
class.

09/10/08 © 2024 Haim Michael All Rights Reserved 70
The Base Class
class SportCar : Car
{
constructor(engine: Engine) : super(engine)
constructor(engine: Engine, attrs: Attributes) : super(engine, attrs)
}

09/10/08 © 2024 Haim Michael All Rights Reserved 71
The open Annotation
The open annotation on a class is the opposite of Java's
final. It allows other classes to inherit from it. By default,
all classes in Kotlin are final.
open class Base(p: Int)
class Derived(p: Int) : Base(p)

09/10/08 © 2024 Haim Michael All Rights Reserved 72
Overriding Methods
Unlike Java, Kotlin requires the explicit open
annotation for overridable members and the explicit
override annotation for the methods that override.
open class Base {
open fun aaa() {}
fun bbb() {}
}
class Derived() : Base() {
override fun aaa() {}
}

09/10/08 © 2024 Haim Michael All Rights Reserved 73
Overriding Methods
The override annotation should be specified
together with the method in the derived class, that
overrides a method in the base class. If there is no
open annotation on the function that was defined in
the base class then it won't be possible to override it.
In a final class (class without the open annotation), it
won't be possible to define open members.

09/10/08 © 2024 Haim Michael All Rights Reserved 74
Declaring Properties
Kotlin allows us to include properties in the class we
define. We can define the property either as a mutable
one by using the var keyword or as a read-only one by
using the val keyword.
Using a property we simply refer to it by referring its
name, as if it was a simple variable.

09/10/08 © 2024 Haim Michael All Rights Reserved 75
Declaring Properties
Apart of the setter and the getter parts, the property
can also have the initializer part.
Fields (AKA instance variables) cannot be declared
directly in our class. When a property we define needs
a backing field Kotlin provides it automatically. The
backing field can be referenced using the field
identified.

09/10/08 © 2024 Haim Michael All Rights Reserved 76
Declaring Properties
class Rectangle {
var width:Double = 10.0
get() = field
set(value) {
if(value>0)
field = value
}
var height:Double = 10.00
get() = field
set(value) {
if(value>0)
field = value
}
val area:Double
get() = this.width * this.height
}

09/10/08 © 2024 Haim Michael All Rights Reserved 77
Declaring Properties
fun main(args: Array<String>) {
var rec = Rectangle()
rec.width = 3.0
rec.height = 4.0
println(rec.area)
}

09/10/08 © 2024 Haim Michael All Rights Reserved 78
Interfaces
The interfaces in Kotlin are very similar to interfaces in
Java8. They can contain both abstract methods and
non abstract ones.
We use the interface keyword when defining a
new interface. Interfaces can be implemented. A class
or an object can implement one (or more) interfaces.

09/10/08 © 2024 Haim Michael All Rights Reserved 79
Interfaces
interface Printable {
fun print()
}
class Student :Printable {
var fName:String = "Mosh"
var lName:String = "Levin"
override fun print() {
println(fName+" "+lName)
}
}
fun main(args: Array<String>) {
var ob = Student()
ob.print()
}

09/10/08 © 2024 Haim Michael All Rights Reserved 80
Visibility Modifiers
There are four visibility modifiers in Kotlin: private,
protected, internal and public.
The default visibility is public. When there isn't any
explicit modifier the visibility would be public.

09/10/08 © 2024 Haim Michael All Rights Reserved 81
Visibility Modifiers inside Packages
When dealing with top level functions, properties, classes,
objects and interface (AKA global): If we don't specify any
visibility modifier, public would be used by default. If we
use the private modifiers then the subject will be visible
inside the file that contains the declaration. If we use
internal it would be visible everywhere in the same
module only. The protected modifier isn't available for
top-level declarations.

09/10/08 © 2024 Haim Michael All Rights Reserved 82
Visibility Modifiers inside Classes
When dealing with functions, properties, classes, objects
and interface defined as members in a specific class or
interface: If we don't specify any visibility modifier, public
would be used by default. If we use the private modifier
then the subject will be visible inside the class only. If we
use protected it would be visible the same as in private and
in addition in subclasses. If we use internal the subject
will be visible inside the module only.

09/10/08 © 2024 Haim Michael All Rights Reserved 83
Data Classes
When marking the class with the data keyword the
compiler will automatically derives the following members
from all properties declared in the primary constructor.
equals() and hashCode()
toString()
componentN() functions
copy() function

09/10/08 © 2024 Haim Michael All Rights Reserved 84
Data Classes
The data classes must fulfill the following requirements:
The primary constructor needs to have at least one parameter
All primary constructor parameters should be marked with val or
var. The data class cannot be abstract, open, sealed or inner.
If there are explicit implementations of equals(), hashCode() or
toString() in the data class body or final implementations in a
super class, then these functions are not generated and the
existing implementations will be used instead.

09/10/08 © 2024 Haim Michael All Rights Reserved 85
Data Classes
If a supertype has the componentN() functions that are
open and return compatible types, the corresponding
functions will be generated for the data class and will
override those of the supertype. If the functions of the
supertype cannot be overridden due to incompatible
signatures or being final and error will be reported.
It isn't allowed to provide our own implementation for the
componentN() and copy() functions.

09/10/08 © 2024 Haim Michael All Rights Reserved 86
Data Classes
data class Book(val title:String, val isbn:Int)
fun main(args:Array<String>) {
var ob = Book("e php",2342334)
println(ob)
}

09/10/08 © 2024 Haim Michael All Rights Reserved 87
Data Classes
If the generated class need to have a parameterless
constructor then we should specify default values for each
one of the properties.
data class Book(val title:String = "noname", val isbn:Int = -1)
fun main(args:Array<String>) {
var ob = Book()
println(ob)
}

09/10/08 © 2024 Haim Michael All Rights Reserved 88
Data Classes
The compiler generates the functions based on the
properties defined inside the primary constructor. It avoids
properties defined within the class body.

09/10/08 © 2024 Haim Michael All Rights Reserved 89
Data Classes
data class Book(val name: String, val isbn: Int) {
var price: Double = 0.0
}
fun main(args:Array<String>) {
var ob = Book("Core PHP",324334)
println(ob)
}

09/10/08 © 2024 Haim Michael All Rights Reserved 90
Sealed Classes
We declare a sealed class by adding the sealed modifier to the
class declaration.
The sealed class can have subclasses but all of them must be
declared inside the same file the sealed class belongs to.
The sealed class should be abstract. It can have abstract
members and it cannot be instantiated.
The sealed class is not allowed to have non private constructors.
Its constructors are private by default.

09/10/08 © 2024 Haim Michael All Rights Reserved 91
Sealed Classes
Sealed classes are highly useful in when statements, as in
the following code sample.
sealed class Expression
data class UnaryOperatorExpression(val operator:String, val
number:Double) : Expression()
data class BinaryOperatorExpression(val operator:String, val
number1:Int, val number2:Int) : Expression()
data class Number(val num:Double) : Expression()

09/10/08 © 2024 Haim Michael All Rights Reserved 92
Sealed Classes
fun evaluate(ob: Expression):Double =
when(ob) {
is UnaryOperatorExpression -> ob.number * 1.0
is Number -> ob.num
is BinaryOperatorExpression -> 1.0 * ob.number1 /
ob.number2
}
fun main(args:Array<String>) {
println(evaluate(Number(3.4)))
}

09/10/08 © 2024 Haim Michael All Rights Reserved 93
Q&A
Thanks for Your Time!
Kotlin Programming
https://lifemichael.com/courses/kotlin
XtremeJ Online Conference
https://xtremej.dev
Java Monthly Review
https://tinyurl.com/javamonthlyreview