SlideShare a Scribd company logo
1 of 47
This work is licensed under the Apache 2.0 License
Kotlin Fundamentals
This work is licensed under the Apache 2.0 License
Compose apps are written in
the Kotlin programming
language.
Kotlin is the language that the
majority of professional Android
developers use to build apps.
This work is licensed under the Apache 2.0 License
Kotlin Playground
Write and run Kotlin code in
the browser.
https://play.kotlinlang.org/
This work is licensed under the Apache 2.0 License
Program
A series of instructions for a
computer to perform some
action.
fun main() {
println("Hello, world!")
}
Output:
Hello, world!
This work is licensed under the Apache 2.0 License
Functions
A function is a segment of a program that
performs a specific task.
You can have many functions in your program
This work is licensed under the Apache 2.0 License
main Function
The main function is the entry
point, or starting point, of the
program.
Start here
fun main() {
println("Hello, world!")
}
Output:
Hello, world!
This work is licensed under the Apache 2.0 License
Defining a function
Functions begin with the fun
keyword.
fun displayIntroduction() {
}
This work is licensed under the Apache 2.0 License
Defining a function
Functions have a name so that
they can be called.
fun displayIntroduction() {
}
This work is licensed under the Apache 2.0 License
Defining a function
Functions need a set of parentheses
after the function name in order to
surround the function inputs or
parameters.
fun displayIntroduction() {
}
This work is licensed under the Apache 2.0 License
Defining a function
The curly braces make up the
function body and contain the
instructions needed to execute
a task.
fun displayIntroduction() {
// Body
}
This work is licensed under the Apache 2.0 License
Putting it together
fun main() {
firstFunction() // Call a function
}
// Define a function
fun firstFunction() {
// Function Body
}
This work is licensed under the Apache 2.0 License
Basic data types
Kotlin Data type What kind of data it can contain Example literal values
String Text
“Add contact”
“Search”
Int Whole integer number
32
-59873
Double Decimal number
2.0
-37123.9999
Float
Decimal number (less precise than a Double).
Has an f or F at the end of the number.
5.0f
-1630.209f
Boolean
true or false. Use this data type when there
are only two possible values.
true
false
This work is licensed under the Apache 2.0 License
A container for a single piece of
data.
Variables
This work is licensed under the Apache 2.0 License
val keyword
Use when you expect the variable value will
not change.
Example: name
var keyword
Use when you expect the variable value can
change.
Example: age
Defining a variable
This work is licensed under the Apache 2.0 License
Defining a variable
Variables start with a var or val
keyword.
fun main() {
val name: String = "Bhavye"
var age: Int = 20
}
This work is licensed under the Apache 2.0 License
Defining a variable
All variables must have a name.
fun main() {
val name: String = "Meghan"
var age: Int = 28
}
This work is licensed under the Apache 2.0 License
Defining a variable
Data type is the type of data
that the variable holds.
fun main() {
val name: String = "Meghan"
var age: Int = 28
}
This work is licensed under the Apache 2.0 License
Defining a variable
The initial value is the value that
is stored in the variable.
fun main() {
val name: String = "Meghan"
var age: Int = 28
// val name = “Meghan”
// var age = 28
}
This work is licensed under the Apache 2.0 License
Defining a variable
If we want to define a variable
with no initial value.
fun main() {
val name: String
var age: Int
// var age => Error
}
This work is licensed under the Apache 2.0 License
Nullability
When we don’t want to assign any value
to a variable, we use ‘null’.
fun main() {
val favoriteActor =
null
}
This work is licensed under the Apache 2.0 License
fun main() {
var favoriteActor :
String = "SRK"
favoriteActor = null
}
⇒ Error generated
Non-nullable and nullable
variables
Nullable types are variables that
can hold null.
Non-null types are variables that
can't hold null.
This work is licensed under the Apache 2.0 License
How to declare a
nullable variable
To declare a nullable variable, you need to explicitly add the nullable type. For
example String?
fun main() {
var favoriteActor:
String? = "Hello"
favoriteActor = null
}
This work is licensed under the Apache 2.0 License
How to handle nullable variables
fun main() {
var favoriteActor: String? = “SRK”
println(favoriteActor.length) // ⇒ Error
println(favoriteActor?.length) // ⇒ No
error
}
This work is licensed under the Apache 2.0 License
Return Value
We have to mention what has to
be returned by the function by
providing the data type for it.
If a function does not return
anything then it is having ‘Unit’
return type
fun firstFunction() : String {
// Body
return “value”
}
This work is licensed under the Apache 2.0 License
Parameters
We can define various parameters or inputs for the function
fun firstFunction(age : Int): Int{
// body
return age
}
fun main(){
// calling the function
}
This work is licensed under the Apache 2.0 License
Function with multiple
parameters
fun firstFunction(age : Int, name : String){
// body
}
fun main(){
firstFucntion(21, “bhavye”)
}
This work is licensed under the Apache 2.0 License
Named arguments
fun firstFunction(age : Int, name : String){
// body
}
fun main(){
firstFunction(name = “bhavye”, age = 20)
}
We need to keep in mind the order of parameters while passing the
arguments so we can use named arguments.
This work is licensed under the Apache 2.0 License
Function with default parameters
fun firstFunction(age : Int, name : String = “noName”){
// body
}
fun main(){
firstFucntion(21, “bhavye”)
firstFunction(21)
}
This work is licensed under the Apache 2.0 License
Arrays
● An array contains multiple values called elements, or sometimes, items.
● The elements in an array are ordered and are accessed with an index.
An array has a fixed size. This means that we can't add elements to an array
beyond this size. We can, however, modify the values at indexes in the array.
This work is licensed under the Apache 2.0 License
val rockPlanets = arrayOf<String>("Mercury", "Venus", "Earth",
"Mars")
println(rockPlanets[0])
Declaration of an Array
This work is licensed under the Apache 2.0 License
Lists
A list is an ordered, resizable collection, typically implemented as a resizable array.
When the array is filled to capacity and you try to insert a new element, the array
is copied to a new bigger array.
This work is licensed under the Apache 2.0 License
listOf()
fun main() {
val solarSystem = listOf("Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn", "Uranus", "Neptune")
println(solarSystem.size)
println(solarSystem.get(3))
println(solarSystem.indexOf("Earth"))
// What happens when we try to find index of an item not
present in the list?
}
This work is licensed under the Apache 2.0 License
val solarSystem = mutableListOf("Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn", "Uranus", "Neptune")
solarSystem.add("Pluto")
solarSystem.add(3, "Theia")
solarSystem[3] = "Future Moon"
solarSystem.removeAt(9)
solarSystem.remove("Future Moon")
println(solarSystem.contains("Pluto"))
This work is licensed under the Apache 2.0 License
Sets
A set is a collection that does
not have a specific order and
doesn't allow duplicate values.
This work is licensed under the Apache 2.0 License
val solarSystem = mutableSetOf("Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn", "Uranus", "Neptune")
println(solarSystem.size)
solarSystem.add("Pluto")
println(solarSystem.size)
solarSystem.add("Pluto")
println(solarSystem.size)
solarSystem.remove("Pluto")
println(solarSystem.contains("Pluto"))
This work is licensed under the Apache 2.0 License
If Statements
This work is licensed under the Apache 2.0 License
This work is licensed under the Apache 2.0 License
If statement :
if (condition) {
}
If/else statement :
if(condition) {
}
else {
}
1.
2.
Else if condition :
if(condition){
}
else if(condition){
}
3.
This work is licensed under the Apache 2.0 License
if/else as an expression :
if(condition)
println(“Text1”)
else println(“Text2”)
message = if(
condition) “Text1”
else
“Text2”
println(message)
This work is licensed under the Apache 2.0 License
When Statement
When statements are preferred when there are more than two branches to consider
This work is licensed under the Apache 2.0 License
fun main() {
val x: Any = 20
when (x) {
2, 3, 5, 7 -> println("x is a prime number between 1 and 10.")
in 1..10 -> println("x is a number between 1 and 10, but not a
prime number.")
is Int -> println("x is an integer number, but not between 1
and 10.")
else -> println("x isn't an integer number.")
}
}
Output:
x is an integer number, but not between 1 and 10.
This work is licensed under the Apache 2.0 License
Classes
A class consists of three major parts :
● Properties. Variables that specify the attributes
of the class's objects.
● Methods. Functions that contain the class's
behaviors and actions.
● Constructors. A special member function that
creates instances of the class throughout the
program in which it's defined.
class Student {
// empty body
}
fun main() {
}
Classes provide blueprints from which objects can be constructed. An object
is an instance of a class that consists of data specific to that object.
This work is licensed under the Apache 2.0 License
Class Objects or Instances
class Student {
// empty body
}
fun main() {
val student1 = Student()
}
This work is licensed under the Apache 2.0 License
Class Methods
class Student {
fun printStudent(){
println(“I am a Student”)
}
}
fun main() {
val student1 = Student()
student1.printStudent()
}
This work is licensed under the Apache 2.0 License
Class Properties
class Student {
var name: String
fun printStudent(){
println(name)
}
}
fun main() {
val student1 = Student()
Student1.name = “Bhavye”
student1.printStudent()
}
This work is licensed under the Apache 2.0 License
Quiz Time!
This work is licensed under the Apache 2.0 License
Break Time!

More Related Content

Similar to Kotlin Fundamentals.pptx

Google Solution Challenge Android Awesomeness.pptx
Google Solution Challenge Android Awesomeness.pptxGoogle Solution Challenge Android Awesomeness.pptx
Google Solution Challenge Android Awesomeness.pptxGoogleDeveloperStude22
 
Android Study Jam Prior Prog S-2
Android Study Jam Prior Prog S-2Android Study Jam Prior Prog S-2
Android Study Jam Prior Prog S-2DSCIGDTUW
 
Introduction to KOTLIN.pptx
Introduction to KOTLIN.pptxIntroduction to KOTLIN.pptx
Introduction to KOTLIN.pptxAkankshaPathak42
 
Session 1 ppt.pptx
Session 1 ppt.pptxSession 1 ppt.pptx
Session 1 ppt.pptxSumit766160
 
Android Development | Compose Camp Day 1 | GDSC SEC Sasaram.pdf
Android Development | Compose Camp Day 1 | GDSC SEC Sasaram.pdfAndroid Development | Compose Camp Day 1 | GDSC SEC Sasaram.pdf
Android Development | Compose Camp Day 1 | GDSC SEC Sasaram.pdfShivamShrey1
 
Compose Camp Day 1.pdf
Compose Camp Day 1.pdfCompose Camp Day 1.pdf
Compose Camp Day 1.pdfShivamShrey1
 
Compose Camp S1.pptx
Compose Camp S1.pptxCompose Camp S1.pptx
Compose Camp S1.pptxGDSCSIT
 
GDSC_day_1.pptx
GDSC_day_1.pptxGDSC_day_1.pptx
GDSC_day_1.pptxGDSCICOER
 
Day3New GDSC.pptx
Day3New GDSC.pptxDay3New GDSC.pptx
Day3New GDSC.pptxGDSCICOER
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
DSC - Android Study Jams - Session 2
DSC - Android Study Jams - Session 2 DSC - Android Study Jams - Session 2
DSC - Android Study Jams - Session 2 vaishnaviayyappan
 
Compose Camp: Introduction to Kotlin.pptx
Compose Camp: Introduction to Kotlin.pptxCompose Camp: Introduction to Kotlin.pptx
Compose Camp: Introduction to Kotlin.pptxAmruthasriAmaravati
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
 

Similar to Kotlin Fundamentals.pptx (20)

-Kotlin Camp Unit2.pptx
-Kotlin Camp Unit2.pptx-Kotlin Camp Unit2.pptx
-Kotlin Camp Unit2.pptx
 
Compose Camp - Session1.pdf
Compose Camp - Session1.pdfCompose Camp - Session1.pdf
Compose Camp - Session1.pdf
 
Google Solution Challenge Android Awesomeness.pptx
Google Solution Challenge Android Awesomeness.pptxGoogle Solution Challenge Android Awesomeness.pptx
Google Solution Challenge Android Awesomeness.pptx
 
Android Study Jam Prior Prog S-2
Android Study Jam Prior Prog S-2Android Study Jam Prior Prog S-2
Android Study Jam Prior Prog S-2
 
Introduction to KOTLIN.pptx
Introduction to KOTLIN.pptxIntroduction to KOTLIN.pptx
Introduction to KOTLIN.pptx
 
Compose 3rd session.pptx
Compose 3rd session.pptxCompose 3rd session.pptx
Compose 3rd session.pptx
 
Compose Camp 2.pdf
Compose Camp 2.pdfCompose Camp 2.pdf
Compose Camp 2.pdf
 
Compose Camp.pdf
Compose Camp.pdfCompose Camp.pdf
Compose Camp.pdf
 
Session 1 ppt.pptx
Session 1 ppt.pptxSession 1 ppt.pptx
Session 1 ppt.pptx
 
Compose Camp Session 1.pdf
Compose Camp Session 1.pdfCompose Camp Session 1.pdf
Compose Camp Session 1.pdf
 
Android Development | Compose Camp Day 1 | GDSC SEC Sasaram.pdf
Android Development | Compose Camp Day 1 | GDSC SEC Sasaram.pdfAndroid Development | Compose Camp Day 1 | GDSC SEC Sasaram.pdf
Android Development | Compose Camp Day 1 | GDSC SEC Sasaram.pdf
 
Compose Camp Day 1.pdf
Compose Camp Day 1.pdfCompose Camp Day 1.pdf
Compose Camp Day 1.pdf
 
Compose Camp S1.pptx
Compose Camp S1.pptxCompose Camp S1.pptx
Compose Camp S1.pptx
 
Javascript
JavascriptJavascript
Javascript
 
GDSC_day_1.pptx
GDSC_day_1.pptxGDSC_day_1.pptx
GDSC_day_1.pptx
 
Day3New GDSC.pptx
Day3New GDSC.pptxDay3New GDSC.pptx
Day3New GDSC.pptx
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
DSC - Android Study Jams - Session 2
DSC - Android Study Jams - Session 2 DSC - Android Study Jams - Session 2
DSC - Android Study Jams - Session 2
 
Compose Camp: Introduction to Kotlin.pptx
Compose Camp: Introduction to Kotlin.pptxCompose Camp: Introduction to Kotlin.pptx
Compose Camp: Introduction to Kotlin.pptx
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 

Recently uploaded

Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectDM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectssuserb6619e
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solidnamansinghjarodiya
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Coursebim.edu.pl
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptbibisarnayak0
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
BSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxBSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxNiranjanYadav41
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectErbil Polytechnic University
 

Recently uploaded (20)

Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectDM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solid
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Course
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.ppt
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
BSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxBSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptx
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction Project
 

Kotlin Fundamentals.pptx

  • 1. This work is licensed under the Apache 2.0 License Kotlin Fundamentals
  • 2. This work is licensed under the Apache 2.0 License Compose apps are written in the Kotlin programming language. Kotlin is the language that the majority of professional Android developers use to build apps.
  • 3. This work is licensed under the Apache 2.0 License Kotlin Playground Write and run Kotlin code in the browser. https://play.kotlinlang.org/
  • 4. This work is licensed under the Apache 2.0 License Program A series of instructions for a computer to perform some action. fun main() { println("Hello, world!") } Output: Hello, world!
  • 5. This work is licensed under the Apache 2.0 License Functions A function is a segment of a program that performs a specific task. You can have many functions in your program
  • 6. This work is licensed under the Apache 2.0 License main Function The main function is the entry point, or starting point, of the program. Start here fun main() { println("Hello, world!") } Output: Hello, world!
  • 7. This work is licensed under the Apache 2.0 License Defining a function Functions begin with the fun keyword. fun displayIntroduction() { }
  • 8. This work is licensed under the Apache 2.0 License Defining a function Functions have a name so that they can be called. fun displayIntroduction() { }
  • 9. This work is licensed under the Apache 2.0 License Defining a function Functions need a set of parentheses after the function name in order to surround the function inputs or parameters. fun displayIntroduction() { }
  • 10. This work is licensed under the Apache 2.0 License Defining a function The curly braces make up the function body and contain the instructions needed to execute a task. fun displayIntroduction() { // Body }
  • 11. This work is licensed under the Apache 2.0 License Putting it together fun main() { firstFunction() // Call a function } // Define a function fun firstFunction() { // Function Body }
  • 12. This work is licensed under the Apache 2.0 License Basic data types Kotlin Data type What kind of data it can contain Example literal values String Text “Add contact” “Search” Int Whole integer number 32 -59873 Double Decimal number 2.0 -37123.9999 Float Decimal number (less precise than a Double). Has an f or F at the end of the number. 5.0f -1630.209f Boolean true or false. Use this data type when there are only two possible values. true false
  • 13. This work is licensed under the Apache 2.0 License A container for a single piece of data. Variables
  • 14. This work is licensed under the Apache 2.0 License val keyword Use when you expect the variable value will not change. Example: name var keyword Use when you expect the variable value can change. Example: age Defining a variable
  • 15. This work is licensed under the Apache 2.0 License Defining a variable Variables start with a var or val keyword. fun main() { val name: String = "Bhavye" var age: Int = 20 }
  • 16. This work is licensed under the Apache 2.0 License Defining a variable All variables must have a name. fun main() { val name: String = "Meghan" var age: Int = 28 }
  • 17. This work is licensed under the Apache 2.0 License Defining a variable Data type is the type of data that the variable holds. fun main() { val name: String = "Meghan" var age: Int = 28 }
  • 18. This work is licensed under the Apache 2.0 License Defining a variable The initial value is the value that is stored in the variable. fun main() { val name: String = "Meghan" var age: Int = 28 // val name = “Meghan” // var age = 28 }
  • 19. This work is licensed under the Apache 2.0 License Defining a variable If we want to define a variable with no initial value. fun main() { val name: String var age: Int // var age => Error }
  • 20. This work is licensed under the Apache 2.0 License Nullability When we don’t want to assign any value to a variable, we use ‘null’. fun main() { val favoriteActor = null }
  • 21. This work is licensed under the Apache 2.0 License fun main() { var favoriteActor : String = "SRK" favoriteActor = null } ⇒ Error generated Non-nullable and nullable variables Nullable types are variables that can hold null. Non-null types are variables that can't hold null.
  • 22. This work is licensed under the Apache 2.0 License How to declare a nullable variable To declare a nullable variable, you need to explicitly add the nullable type. For example String? fun main() { var favoriteActor: String? = "Hello" favoriteActor = null }
  • 23. This work is licensed under the Apache 2.0 License How to handle nullable variables fun main() { var favoriteActor: String? = “SRK” println(favoriteActor.length) // ⇒ Error println(favoriteActor?.length) // ⇒ No error }
  • 24. This work is licensed under the Apache 2.0 License Return Value We have to mention what has to be returned by the function by providing the data type for it. If a function does not return anything then it is having ‘Unit’ return type fun firstFunction() : String { // Body return “value” }
  • 25. This work is licensed under the Apache 2.0 License Parameters We can define various parameters or inputs for the function fun firstFunction(age : Int): Int{ // body return age } fun main(){ // calling the function }
  • 26. This work is licensed under the Apache 2.0 License Function with multiple parameters fun firstFunction(age : Int, name : String){ // body } fun main(){ firstFucntion(21, “bhavye”) }
  • 27. This work is licensed under the Apache 2.0 License Named arguments fun firstFunction(age : Int, name : String){ // body } fun main(){ firstFunction(name = “bhavye”, age = 20) } We need to keep in mind the order of parameters while passing the arguments so we can use named arguments.
  • 28. This work is licensed under the Apache 2.0 License Function with default parameters fun firstFunction(age : Int, name : String = “noName”){ // body } fun main(){ firstFucntion(21, “bhavye”) firstFunction(21) }
  • 29. This work is licensed under the Apache 2.0 License Arrays ● An array contains multiple values called elements, or sometimes, items. ● The elements in an array are ordered and are accessed with an index. An array has a fixed size. This means that we can't add elements to an array beyond this size. We can, however, modify the values at indexes in the array.
  • 30. This work is licensed under the Apache 2.0 License val rockPlanets = arrayOf<String>("Mercury", "Venus", "Earth", "Mars") println(rockPlanets[0]) Declaration of an Array
  • 31. This work is licensed under the Apache 2.0 License Lists A list is an ordered, resizable collection, typically implemented as a resizable array. When the array is filled to capacity and you try to insert a new element, the array is copied to a new bigger array.
  • 32. This work is licensed under the Apache 2.0 License listOf() fun main() { val solarSystem = listOf("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune") println(solarSystem.size) println(solarSystem.get(3)) println(solarSystem.indexOf("Earth")) // What happens when we try to find index of an item not present in the list? }
  • 33. This work is licensed under the Apache 2.0 License val solarSystem = mutableListOf("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune") solarSystem.add("Pluto") solarSystem.add(3, "Theia") solarSystem[3] = "Future Moon" solarSystem.removeAt(9) solarSystem.remove("Future Moon") println(solarSystem.contains("Pluto"))
  • 34. This work is licensed under the Apache 2.0 License Sets A set is a collection that does not have a specific order and doesn't allow duplicate values.
  • 35. This work is licensed under the Apache 2.0 License val solarSystem = mutableSetOf("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune") println(solarSystem.size) solarSystem.add("Pluto") println(solarSystem.size) solarSystem.add("Pluto") println(solarSystem.size) solarSystem.remove("Pluto") println(solarSystem.contains("Pluto"))
  • 36. This work is licensed under the Apache 2.0 License If Statements
  • 37. This work is licensed under the Apache 2.0 License
  • 38. This work is licensed under the Apache 2.0 License If statement : if (condition) { } If/else statement : if(condition) { } else { } 1. 2. Else if condition : if(condition){ } else if(condition){ } 3.
  • 39. This work is licensed under the Apache 2.0 License if/else as an expression : if(condition) println(“Text1”) else println(“Text2”) message = if( condition) “Text1” else “Text2” println(message)
  • 40. This work is licensed under the Apache 2.0 License When Statement When statements are preferred when there are more than two branches to consider
  • 41. This work is licensed under the Apache 2.0 License fun main() { val x: Any = 20 when (x) { 2, 3, 5, 7 -> println("x is a prime number between 1 and 10.") in 1..10 -> println("x is a number between 1 and 10, but not a prime number.") is Int -> println("x is an integer number, but not between 1 and 10.") else -> println("x isn't an integer number.") } } Output: x is an integer number, but not between 1 and 10.
  • 42. This work is licensed under the Apache 2.0 License Classes A class consists of three major parts : ● Properties. Variables that specify the attributes of the class's objects. ● Methods. Functions that contain the class's behaviors and actions. ● Constructors. A special member function that creates instances of the class throughout the program in which it's defined. class Student { // empty body } fun main() { } Classes provide blueprints from which objects can be constructed. An object is an instance of a class that consists of data specific to that object.
  • 43. This work is licensed under the Apache 2.0 License Class Objects or Instances class Student { // empty body } fun main() { val student1 = Student() }
  • 44. This work is licensed under the Apache 2.0 License Class Methods class Student { fun printStudent(){ println(“I am a Student”) } } fun main() { val student1 = Student() student1.printStudent() }
  • 45. This work is licensed under the Apache 2.0 License Class Properties class Student { var name: String fun printStudent(){ println(name) } } fun main() { val student1 = Student() Student1.name = “Bhavye” student1.printStudent() }
  • 46. This work is licensed under the Apache 2.0 License Quiz Time!
  • 47. This work is licensed under the Apache 2.0 License Break Time!

Editor's Notes

  1. To make it easier for you to learn, you’ll be writing your code in the Kotlin Playground which you can access via the web browser. The site looks something like this. You can write your code in this window and run it by hitting the green Run button. The result of your code (known as the output) will show up at the bottom of the window (where it says “Hello, world!”). To illustrate a few important concepts that you’ll learn in this pathway, we will go through a short code demo to create a program in Kotlin.
  2. In Kotlin Playground, you will learn to explore and modify simple programs in Kotlin. You can think of a program as a series of instructions for a computer or mobile device to perform some action. In this program, the action is printing “Hello, world!”.
  3. A function is a segment of a program that performs a specific task. You can have many functions in your program or only a single one. Creating separate functions for specific tasks has a number of benefits. Reusable code: Rather than copying and pasting code that you need to use more than once, you can simply call a function wherever needed. Readability: Ensuring functions do one and only one specific task helps other developers and teammates, as well as your future self to know exactly what a piece of code does.
  4. A Kotlin program is required to have a main function, which is the entry point, or starting point, of the program. You may be asking what a function is…
  5. We will demonstrate how to define a function with a function called displayIntroduction() that we will use to print our name and age. A function definition starts with the fun keyword. A keyword is a reserved word that has a special meaning in Kotlin, in this case the fun keyword tells Kotlin that you are going to make a function.
  6. Functions need to have a descriptive name so that they can be called from other parts of the program.
  7. Functions need a set of parentheses which you can use to optionally pass information into the function. displayIntroduction() won’t need information passed in. You will learn more about passing in inputs into functions later in the course.
  8. Functions need curly braces that contain the instructions needed to execute a task.
  9. Finally, we will replace the contents of the main() function with a call to the displayIntroduction() function when we run it, “Hi I’m Meghan and I am 28 years old” will print to the output. In this lecture we went over functions and variables and how to put them together to create a function that introduces you. Soon you will go deeper into these concepts and try them out for yourself in the codelabs.
  10. When you decide what aspects of your app can be variables, it's important to specify what type of data can be stored in those variables. In Kotlin, there are some common basic data types. This table shows a different data type in each row. For each data type, there's a description of what kind of data it can hold and example values. A String holds text so you will use it to store your name, and an Int holds an integer number so you will use it to store your age.
  11. In computer programming, a variable is a container for a single piece of data. You can envision it as a box that contains a value. The box has a label, which is the name of the variable. By referring to the box by its name, you have access to the value it holds.
  12. Now, let’s jump into how you define a variable. You can declare a variable using either val or var. With val, the variable is read-only, which means you can only read, or access, the value of the variable. Once the value is set, you cannot edit or modify its value. With var, the variable is mutable, which means the value can be changed or modified. The value can be mutated. In Kotlin, it's preferred to use val over var when possible. We will store your name as a val because that will not change. We will store your age as a var because it changes every year.
  13. To demonstrate how to define a variable we will define both name and age variables. Before you use a variable, you must declare it. To declare a variable, start with the val or var keyword.
  14. All variables must have a name that they can be referenced by.
  15. The data type specifies the type of data that the variable holds. Note that a colon separates the name and data type.
  16. In the variable declaration, the equal sign symbol (=) follows the data type. The equal sign symbol is called the assignment operator. The assignment operator assigns a value to the variable. The variable’s initial value is the data stored in the variable.
  17. In the variable declaration, the equal sign symbol (=) follows the data type. The equal sign symbol is called the assignment operator. The assignment operator assigns a value to the variable. The variable’s initial value is the data stored in the variable.
  18. In the variable declaration, the equal sign symbol (=) follows the data type. The equal sign symbol is called the assignment operator. The assignment operator assigns a value to the variable. The variable’s initial value is the data stored in the variable.
  19. In the variable declaration, the equal sign symbol (=) follows the data type. The equal sign symbol is called the assignment operator. The assignment operator assigns a value to the variable. The variable’s initial value is the data stored in the variable.
  20. In the variable declaration, the equal sign symbol (=) follows the data type. The equal sign symbol is called the assignment operator. The assignment operator assigns a value to the variable. The variable’s initial value is the data stored in the variable.
  21. In the variable declaration, the equal sign symbol (=) follows the data type. The equal sign symbol is called the assignment operator. The assignment operator assigns a value to the variable. The variable’s initial value is the data stored in the variable.
  22. In the variable declaration, the equal sign symbol (=) follows the data type. The equal sign symbol is called the assignment operator. The assignment operator assigns a value to the variable. The variable’s initial value is the data stored in the variable.