SlideShare uma empresa Scribd logo
1 de 30
Baixar para ler offline
Intro to Kotlin
Magda Miu
● Properties (val, var)
● String templates
● Null Safety
● Smart Cast
● OOP
● Lambdas
● Collections
● Extensions
● Infix Notation
● Operator Overloading
Agenda
What is Kotlin?
● Statically typed language
● From Jetbrains
● Inspired by Java, Scala, C#, Groovy etc.
● Targets: JVM and Javascript
1.0
Release
1.1
Release
Kotlin is
born
Gradle
Android
Official
Spring
Timeline (Kotlin 1.1.4 is out)
Chart source: https://github.com/jetbrains/kotlin-workshop
Conventions
• The same conventions like on Java
• Uppercase for types
• Lower camelCase for methods and properties
• Semicolons are optional
• Reverse notation for packages
• A file could contain multiple classes
• The folder names not have to match the package name
Development tools
• JDK
• Version 6, 7, 8 and 9
• Kotlin Compiler
• Editor or IDE
• IntelliJ IDEA, Android Studio, NetBeans, Eclipse
Build tools
• Maven
• Gradle
• Kobalt
• Ant
• Command Line
Basic Data Types
Numbers
Characters
Booleans
Arrays
Strings
Any
Nothing
Properties: val and var
• val is immutable (read-only) and you can only assign a value to them exactly
one time. This is the recommended type to use.
• var is mutable and can be reassigned.
• The type inference is more powerful than Java
• Unit in Kotlin corresponds to the void in Java. Unit is a real class (Singleton)
with only one instance.
• Nothing is a type in Kotlin that represents “a value that never exists”, that
means just “no value at all”.
private final int a = 1;
private int b = 2;
private final int c = 3;
private int d = 4;
public int getA() { return a; }
public int getB() { return b; }
public void setB(int b) { this.b = b; }
public int getC() { return c; }
public int getD() { return d; }
public void setD(int d) { this.d = d; }
val a: Int = 1
var b: Int = 2
val c = 3
var d = 4
Properties: val and var
String templates
• Kotlin supports template expressions
• Simple reference uses $
• Complex references uses ${}
• Raw Strings
class KotlinClass {
fun main(args: Array<String>) {
val first = "Intro to"
val second = "Koltin"
var both = "$first $second"
println("$both has ${both.length}")
println(""""$both" has ${both.length}""")
}
}
/*
1. Menu>Tools>Kotlin>Show Kotlin Bytecode
2. Click on the Decompile button
3. See the java code */
String templates
Public final class JavaClass {
public final void main(@NotNull String[]
args) {
Intrinsics.checkParameterIsNotNull(args,
"args");
String first = "Intro to";
String second = "Koltin";
String both = "" + first + ' ' + second;
String var5 = "" + both + " has " +
both.length();
System.out.println(var5);
var5 = '"' + both + "" has " +
both.length();
System.out.println(var5);
}
}
Null safety
• No more NPEs
• Possible causes for NPE:
• !!
• throw NullPointerException();
• External Java code
• Data inconsistency with regard to initialization
Null safety
• No more NPEs
• Possible causes for NPE:
• !!
• throw NullPointerException();
• External Java code
• Data inconsistency with regard to initialization
class KotlinClass {
val notNullString: String = null //error!
val nullableString: String? = null
//condition checks
var theString: String? = "abc"
val length1 = if (theString != null)
theString.length else -1
//safe calls
val length2 = theString?.length
//elvis operator
val length3 = theString?.length ?: -1
//use !!
val length4 = theString!!.length
//safe casts
val aInt: Int? = theString as? Int
}
Class
• Many classes in the same file
• Classes and methods are final by default. Use open for extensibility.
• Only properties(public by default) and functions(fun)
• No new keyword on instantiation
• lateinit for properties (not null) and they should be mutable
• init block is equal with the constructor in Java
• inner keyword to be able to access members of the surrounding class
class KotlinClass(var name: String) {
lateinit var gdg: GDGPitesti
val language: String
init {
language = "Kotlin"
}
fun initializeName (name: String) {
gdg = GDGPitesti(name)
}
inner class GDGPitesti(val text: String)
fun sayItFromGDG(): String = "${gdg.text}
$name $language"
}
fun main(args: Array<String>) {
var a = KotlinClass("loves")
a.initializeName("GDG Pitesti")
print(a.sayItFromGDG())//GDG Pitesti loves Kotlin
}
Class
public final class JavaClass {
@NotNull
public KotlinClass.GDGPitesti gdg;
@NotNull
private final String language;
@NotNull
private String name;
@NotNull
public final KotlinClass.GDGPitesti getGdg() {
KotlinClass.GDGPitesti var10000 = this.gdg;
if(this.gdg == null) {
Intrinsics.throwUninitializedPropertyAccessExcept
ion("gdg");
}
return var10000;
}
…
Data Class
• data class contains:
• properties
• equals
• hashCode
• toString
• copy
• component (Destructuring Declarations)
data class Coordinate(var lat: Double, var lon:
Double)
fun main(args: Array<String>) {
val city1 = Coordinate(24.5, 48.5)
//copy
val city2 = city1.copy(lat = 25.7)
//component
val (theLat, theLon) = city2
println(city1)
println(city2)
println(theLat)
println(theLon)
}
Data Class
public final class CoordinateJava {
private double lat;
private double lon;
public final double getLat() {
return this.lat;
}
public final void setLat(double var1) {
this.lat = var1;
}
public final double getLon() {
return this.lon;
}
public final void setLon(double var1) {
this.lon = var1;
}
….
Interface
• Could contain abstract methods and/or properties
• They need to be initialized in the implementing class in order to respect the
contract of the interface
• override keyword is mandatory
• A property declared in an interface can either be abstract, or it can provide
implementations for accessors.
interface GDG {
val name: String
fun getCity(): String
}
class GDGPitesti: GDG{
override val name: String = "GDG"
override fun getCity(): String = "$name
Pitesti"
}
fun main(args: Array<String>) {
println(GDGPitesti().getCity())
}
Interface
Object
• The object keyword creates singleton in Kotlin
• An object declaration inside a class can be marked with the companion keyword
• Members of the companion object can be called by using simply the class name
as the qualifier (like static on Java)
• The name of the companion object can be omitted, in which case the name
Companion will be used
object SingletonClass {
fun getHello(): String = "Hello Singleton"
}
class CompaniedClass(val str: String) {
companion object Printer {
fun getHello(): String = "Hello Companion"
}
}
class NoNameCompaniedClass(val str: String) {
companion object {
fun getHello(): String = "Hello No Name
Companion"
}
}
fun main(args: Array<String>) {
SingletonClass.getHello() // Hello Singleton
CompaniedClass.getHello() // Hello Companion
NoNameCompaniedClass.getHello() // Hello No
Name Companion
}
Object
fun main(args: Array<String>) {
val a = 4; val b = 7
val max = if (a > b) {
println("$a is grater than $b"); a
} else {
println("$b is grater than $a"); b
}
println(max)
println(describe("GDG"))
for (i in 1..10 step 2) {
print("$i ")
}}
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Awesome"
}
It’s all about expressions...
Collections and Lambdas
• Kotlin distinguishes between
mutable and immutable
collections
• The supported operations on
Collections are: map,
flatMap, forEach, fold,
reduce, filter, zip etc.
• to is in infix function
fun main(args: Array<String>) {
listOf(1, 2, 3); mutableListOf("a", "b", "c")
setOf(1, 2, 3); mutableSetOf("a", "b", "c")
mapOf(1 to "a", 2 to "b", 3 to "c")
mutableMapOf("a" to 1, "b" to 2, "c" to 3)
val aList = listOf(1, 2, 4)
println(aList.map { elem ->
elem + 1
})
println(aList)
println(aList.filter { it != 1 })
fun sum(a: Int, b: Int) = a + b
println(aList.reduce(::sum))
}
Extensions functions
• Add operators to the classes by
using the operator
• Create infix functions with the
infix keyword
• Extension functions are normal
static methods bearing no
connection with the class they are
extending, other than taking an
instance of this class as a
parameters
fun main(args: Array<String>) {
val x = "Kotlin"
println(x.last())
val m1 = Matrix(1, 2, 3, 4)
val m2 = Matrix(1, 1, 1, 1)
val m3 = m1 + m2
println("${m3.a} ${m3.b} ${m3.c} ${m3.d}")
}
fun String.last(): Char {
return this[length - 1]
}
class Matrix(val a: Int, val b: Int, val c: Int,
val d: Int) {
operator fun plus(matrix: Matrix): Matrix {
return Matrix(a + matrix.a, b + matrix.b,
c + matrix.c, d + matrix.d)
}
}
Questions?
Resources
● Images source: buzzfeed.com
● http://jussi.hallila.com/Kollections/
● https://try.kotlinlang.org
● https://kotlinlang.org/docs/books.html

Mais conteúdo relacionado

Mais procurados

Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better JavaGarth Gilmour
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
BangaloreJUG introduction to kotlin
BangaloreJUG   introduction to kotlinBangaloreJUG   introduction to kotlin
BangaloreJUG introduction to kotlinChandra Sekhar Nayak
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
 
Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Arnaud Giuliani
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designAndrey Breslav
 
Building microservices with Kotlin
Building microservices with KotlinBuilding microservices with Kotlin
Building microservices with KotlinHaim Yadid
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
Summer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcampSummer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcampKai Koenig
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin XPeppers
 

Mais procurados (19)

Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
BangaloreJUG introduction to kotlin
BangaloreJUG   introduction to kotlinBangaloreJUG   introduction to kotlin
BangaloreJUG introduction to kotlin
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017
 
Fall in love with Kotlin
Fall in love with KotlinFall in love with Kotlin
Fall in love with Kotlin
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language design
 
Building microservices with Kotlin
Building microservices with KotlinBuilding microservices with Kotlin
Building microservices with Kotlin
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Summer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcampSummer of Tech 2017 - Kotlin/Android bootcamp
Summer of Tech 2017 - Kotlin/Android bootcamp
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 

Semelhante a Intro to Kotlin

Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaDILo Surabaya
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
Ceylon - the language and its tools
Ceylon - the language and its toolsCeylon - the language and its tools
Ceylon - the language and its toolsMax Andersen
 
Kotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonKotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonEd Austin
 
KotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptxKotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptxIan Robertson
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Kotlin fundamentals - By: Ipan Ardian
Kotlin fundamentals - By: Ipan ArdianKotlin fundamentals - By: Ipan Ardian
Kotlin fundamentals - By: Ipan ArdianRizal Khilman
 
Kotlin Fundamentals
Kotlin Fundamentals Kotlin Fundamentals
Kotlin Fundamentals Ipan Ardian
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.pptKhizar40
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developersMohamed Wael
 
Java tutorials
Java tutorialsJava tutorials
Java tutorialssaryu2011
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android DevelopmentSpeck&Tech
 

Semelhante a Intro to Kotlin (20)

Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Introduction to Kotlin
Introduction to KotlinIntroduction to Kotlin
Introduction to Kotlin
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo Surabaya
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Ceylon - the language and its tools
Ceylon - the language and its toolsCeylon - the language and its tools
Ceylon - the language and its tools
 
Kotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonKotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparison
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
KotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptxKotlinForJavaDevelopers-UJUG.pptx
KotlinForJavaDevelopers-UJUG.pptx
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Kotlin fundamentals - By: Ipan Ardian
Kotlin fundamentals - By: Ipan ArdianKotlin fundamentals - By: Ipan Ardian
Kotlin fundamentals - By: Ipan Ardian
 
Kotlin Fundamentals
Kotlin Fundamentals Kotlin Fundamentals
Kotlin Fundamentals
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
core java
core javacore java
core java
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
 

Último

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Intro to Kotlin

  • 2.
  • 3.
  • 4. ● Properties (val, var) ● String templates ● Null Safety ● Smart Cast ● OOP ● Lambdas ● Collections ● Extensions ● Infix Notation ● Operator Overloading Agenda
  • 5. What is Kotlin? ● Statically typed language ● From Jetbrains ● Inspired by Java, Scala, C#, Groovy etc. ● Targets: JVM and Javascript
  • 6. 1.0 Release 1.1 Release Kotlin is born Gradle Android Official Spring Timeline (Kotlin 1.1.4 is out) Chart source: https://github.com/jetbrains/kotlin-workshop
  • 7. Conventions • The same conventions like on Java • Uppercase for types • Lower camelCase for methods and properties • Semicolons are optional • Reverse notation for packages • A file could contain multiple classes • The folder names not have to match the package name
  • 8. Development tools • JDK • Version 6, 7, 8 and 9 • Kotlin Compiler • Editor or IDE • IntelliJ IDEA, Android Studio, NetBeans, Eclipse
  • 9. Build tools • Maven • Gradle • Kobalt • Ant • Command Line
  • 10.
  • 12. Properties: val and var • val is immutable (read-only) and you can only assign a value to them exactly one time. This is the recommended type to use. • var is mutable and can be reassigned. • The type inference is more powerful than Java • Unit in Kotlin corresponds to the void in Java. Unit is a real class (Singleton) with only one instance. • Nothing is a type in Kotlin that represents “a value that never exists”, that means just “no value at all”.
  • 13. private final int a = 1; private int b = 2; private final int c = 3; private int d = 4; public int getA() { return a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public int getD() { return d; } public void setD(int d) { this.d = d; } val a: Int = 1 var b: Int = 2 val c = 3 var d = 4 Properties: val and var
  • 14. String templates • Kotlin supports template expressions • Simple reference uses $ • Complex references uses ${} • Raw Strings
  • 15. class KotlinClass { fun main(args: Array<String>) { val first = "Intro to" val second = "Koltin" var both = "$first $second" println("$both has ${both.length}") println(""""$both" has ${both.length}""") } } /* 1. Menu>Tools>Kotlin>Show Kotlin Bytecode 2. Click on the Decompile button 3. See the java code */ String templates Public final class JavaClass { public final void main(@NotNull String[] args) { Intrinsics.checkParameterIsNotNull(args, "args"); String first = "Intro to"; String second = "Koltin"; String both = "" + first + ' ' + second; String var5 = "" + both + " has " + both.length(); System.out.println(var5); var5 = '"' + both + "" has " + both.length(); System.out.println(var5); } }
  • 16. Null safety • No more NPEs • Possible causes for NPE: • !! • throw NullPointerException(); • External Java code • Data inconsistency with regard to initialization
  • 17. Null safety • No more NPEs • Possible causes for NPE: • !! • throw NullPointerException(); • External Java code • Data inconsistency with regard to initialization class KotlinClass { val notNullString: String = null //error! val nullableString: String? = null //condition checks var theString: String? = "abc" val length1 = if (theString != null) theString.length else -1 //safe calls val length2 = theString?.length //elvis operator val length3 = theString?.length ?: -1 //use !! val length4 = theString!!.length //safe casts val aInt: Int? = theString as? Int }
  • 18. Class • Many classes in the same file • Classes and methods are final by default. Use open for extensibility. • Only properties(public by default) and functions(fun) • No new keyword on instantiation • lateinit for properties (not null) and they should be mutable • init block is equal with the constructor in Java • inner keyword to be able to access members of the surrounding class
  • 19. class KotlinClass(var name: String) { lateinit var gdg: GDGPitesti val language: String init { language = "Kotlin" } fun initializeName (name: String) { gdg = GDGPitesti(name) } inner class GDGPitesti(val text: String) fun sayItFromGDG(): String = "${gdg.text} $name $language" } fun main(args: Array<String>) { var a = KotlinClass("loves") a.initializeName("GDG Pitesti") print(a.sayItFromGDG())//GDG Pitesti loves Kotlin } Class public final class JavaClass { @NotNull public KotlinClass.GDGPitesti gdg; @NotNull private final String language; @NotNull private String name; @NotNull public final KotlinClass.GDGPitesti getGdg() { KotlinClass.GDGPitesti var10000 = this.gdg; if(this.gdg == null) { Intrinsics.throwUninitializedPropertyAccessExcept ion("gdg"); } return var10000; } …
  • 20. Data Class • data class contains: • properties • equals • hashCode • toString • copy • component (Destructuring Declarations)
  • 21. data class Coordinate(var lat: Double, var lon: Double) fun main(args: Array<String>) { val city1 = Coordinate(24.5, 48.5) //copy val city2 = city1.copy(lat = 25.7) //component val (theLat, theLon) = city2 println(city1) println(city2) println(theLat) println(theLon) } Data Class public final class CoordinateJava { private double lat; private double lon; public final double getLat() { return this.lat; } public final void setLat(double var1) { this.lat = var1; } public final double getLon() { return this.lon; } public final void setLon(double var1) { this.lon = var1; } ….
  • 22. Interface • Could contain abstract methods and/or properties • They need to be initialized in the implementing class in order to respect the contract of the interface • override keyword is mandatory • A property declared in an interface can either be abstract, or it can provide implementations for accessors.
  • 23. interface GDG { val name: String fun getCity(): String } class GDGPitesti: GDG{ override val name: String = "GDG" override fun getCity(): String = "$name Pitesti" } fun main(args: Array<String>) { println(GDGPitesti().getCity()) } Interface
  • 24. Object • The object keyword creates singleton in Kotlin • An object declaration inside a class can be marked with the companion keyword • Members of the companion object can be called by using simply the class name as the qualifier (like static on Java) • The name of the companion object can be omitted, in which case the name Companion will be used
  • 25. object SingletonClass { fun getHello(): String = "Hello Singleton" } class CompaniedClass(val str: String) { companion object Printer { fun getHello(): String = "Hello Companion" } } class NoNameCompaniedClass(val str: String) { companion object { fun getHello(): String = "Hello No Name Companion" } } fun main(args: Array<String>) { SingletonClass.getHello() // Hello Singleton CompaniedClass.getHello() // Hello Companion NoNameCompaniedClass.getHello() // Hello No Name Companion } Object
  • 26. fun main(args: Array<String>) { val a = 4; val b = 7 val max = if (a > b) { println("$a is grater than $b"); a } else { println("$b is grater than $a"); b } println(max) println(describe("GDG")) for (i in 1..10 step 2) { print("$i ") }} fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Awesome" } It’s all about expressions...
  • 27. Collections and Lambdas • Kotlin distinguishes between mutable and immutable collections • The supported operations on Collections are: map, flatMap, forEach, fold, reduce, filter, zip etc. • to is in infix function fun main(args: Array<String>) { listOf(1, 2, 3); mutableListOf("a", "b", "c") setOf(1, 2, 3); mutableSetOf("a", "b", "c") mapOf(1 to "a", 2 to "b", 3 to "c") mutableMapOf("a" to 1, "b" to 2, "c" to 3) val aList = listOf(1, 2, 4) println(aList.map { elem -> elem + 1 }) println(aList) println(aList.filter { it != 1 }) fun sum(a: Int, b: Int) = a + b println(aList.reduce(::sum)) }
  • 28. Extensions functions • Add operators to the classes by using the operator • Create infix functions with the infix keyword • Extension functions are normal static methods bearing no connection with the class they are extending, other than taking an instance of this class as a parameters fun main(args: Array<String>) { val x = "Kotlin" println(x.last()) val m1 = Matrix(1, 2, 3, 4) val m2 = Matrix(1, 1, 1, 1) val m3 = m1 + m2 println("${m3.a} ${m3.b} ${m3.c} ${m3.d}") } fun String.last(): Char { return this[length - 1] } class Matrix(val a: Int, val b: Int, val c: Int, val d: Int) { operator fun plus(matrix: Matrix): Matrix { return Matrix(a + matrix.a, b + matrix.b, c + matrix.c, d + matrix.d) } }
  • 30. Resources ● Images source: buzzfeed.com ● http://jussi.hallila.com/Kollections/ ● https://try.kotlinlang.org ● https://kotlinlang.org/docs/books.html