SlideShare a Scribd company logo
Kotlin for Android
May 24, 2018
y/kotlin-workbook
Objects, Constructors and Control Flow
y/kotlin-workbook
classes
BASIC SYNTAX
y/kotlin-workbook
interface Runnable {
fun run()
}
interface RepeatingRunnable : Runnable {
fun run(times: Int) {
(1..times).forEach { run() }
}
}
open class Greeting : Runnable {
override fun run() = println("Hi!")
}
class RepeatingGreeting : Greeting(), RepeatingRunnable
RepeatingGreeting().run(3)
● One primary constructor as part of class declaration
○ Declare property visibility and default values in the
parameter list
constructors
OBJECTS AND FLOW
y/kotlin-workbook
class Person(
val name: String = "John",
private var age: Int
)
● One primary constructor as part of class declaration
○ Declare property visibility and default values in the
parameter list
● Initialization blocks - init
constructors
OBJECTS AND FLOW
y/kotlin-workbook
class Person(
val name: String = "John",
private var age: Int
){
init {
// Initialize things here...
}
}
● One primary constructor as part of class declaration
○ Declare property visibility and default values in the
parameter list
● Initialization blocks - init
● Optional secondary constructors
● Property initialization
constructors
OBJECTS AND FLOW
y/kotlin-workbook
class Person(
val name: String = "John",
private var age: Int
){
var hairColor: Color = Color.BLACK
init {
// Initialize things here...
}
constructor(age: Int, hairColor: Color): this(age = age){
this.hairColor = hairColor
}
}
constructors
OBJECTS AND FLOW
y/kotlin-workbook
DEMO
object
OBJECTS AND FLOW
y/kotlin-workbook
● Used to create anonymous inner classes and singletons
● Can have static methods in the JVM
● Can have static fields in the JVM
● Every class can have a companion object
● Cannot inherit from object
○ object can inherit and extend though
object
OBJECTS AND FLOW
y/kotlin-workbook
object Foo {
val BAR = "BAR"
fun hi() = "hi"
}
// kotlin
val bar = Foo.BAR
val foo = Foo.hi()
// java
String bar = Foo.INSTANCE.BAR;
String foo = Foo.INSTANCE.hi();
object
OBJECTS AND FLOW
y/kotlin-workbook
object Foo {
const val BAR = "BAR"
@JvmStatic fun hi() = "hi"
}
// kotlin
val bar = Foo.BAR
val foo = Foo.hi()
// java
String bar = Foo.INSTANCE.BAR;
String foo = Foo.INSTANCE.hi();
// java improved interop
String bar = Foo.BAR;
String foo = Foo.hi();
companion object
advanced
OBJECTS AND FLOW
y/kotlin-workbook
UserRepo.intance() // returns the real repo
BizRepo.intance() // returns the real repo
UserRepo.mock = mock(UserRepo)
BizRepo.mock = mock(BizRepo)
UserRepo.intance() // returns the mock repo
BizRepo.intance() // returns the mock repo
UserRepo.mock = null
BizRepo.mock = null
UserRepo.intance() // returns the real repo
BizRepo.intance() // returns the real repo
companion object
advanced
OBJECTS AND FLOW
y/kotlin-workbook
interface Factory<T: Any> {
var mock: T?
fun instance(): T
}
UserRepo.intance() // returns the real repo
BizRepo.intance() // returns the real repo
UserRepo.mock = mock(UserRepo)
BizRepo.mock = mock(BizRepo)
UserRepo.intance() // returns the mock repo
BizRepo.intance() // returns the mock repo
UserRepo.mock = null
BizRepo.mock = null
UserRepo.intance() // returns the real repo
BizRepo.intance() // returns the real repo
companion object
advanced
OBJECTS AND FLOW
y/kotlin-workbook
interface Factory<T: Any> {
var mock: T?
fun instance(): T
}
open class Provider<T: Any>(init: () -> T): Factory<T> {
override var mock: T? = null
private val instance: T by lazy(init)
override fun instance() = mock ?: instance
}
UserRepo.intance() // returns the real repo
BizRepo.intance() // returns the real repo
UserRepo.mock = mock(UserRepo)
BizRepo.mock = mock(BizRepo)
UserRepo.intance() // returns the mock repo
BizRepo.intance() // returns the mock repo
UserRepo.mock = null
BizRepo.mock = null
UserRepo.intance() // returns the real repo
BizRepo.intance() // returns the real repo
companion object
advanced
OBJECTS AND FLOW
y/kotlin-workbook
interface Factory<T: Any> {
var mock: T?
fun instance(): T
}
open class Provider<T: Any>(init: () -> T): Factory<T> {
override var mock: T? = null
private val instance: T by lazy(init)
override fun instance() = mock ?: instance
}
class UserRepo {
companion object : Provider<UserRepo>({ UserRepo() })
}
class BizRepo {
companion object : Provider<BizRepo>({ BizRepo() })
}
UserRepo.intance() // returns the real repo
BizRepo.intance() // returns the real repo
UserRepo.mock = mock(UserRepo)
BizRepo.mock = mock(BizRepo)
UserRepo.intance() // returns the mock repo
BizRepo.intance() // returns the mock repo
UserRepo.mock = null
BizRepo.mock = null
UserRepo.intance() // returns the real repo
BizRepo.intance() // returns the real repo
● No goto
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return
print(it)
}
println(" this is unreachable")
}
● No goto
● return, break and continue
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return
print(it)
}
println(" this is unreachable")
}
// 12
● No goto
● return, break and continue
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@forEach
print(it)
}
println(" this is reachable")
}
● No goto
● return, break and continue can use labels
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@forEach
print(it)
}
println(" this is reachable")
}
// 1245 this is reachable
● No goto
● return, break and continue can use labels
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
fun foo() {
listOf(1, 2, 3, 4, 5).forEach loop@{
if (it == 3) return@loop
print(it)
}
println(" this is reachable")
}
// 1245 this is reachable
● No goto
● return, break and continue can use labels
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
fun foo() {
listOf(1, 2, 3, 4, 5).run { forEach {
if (it == 3) return@run
print(it)
}}
println(" this is reachable")
}
// 12 this is reachable
● No goto
● return, break and continue can use labels
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
fun foo() {
for (int in listOf(1, 2, 3, 4, 5)) {
if (int == 3) break
print(int)
}
println(" this is reachable")
}
● No goto
● return, break and continue can use labels
● for loop - no parameterized for(;;)
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
● No goto
● return, break and continue can use labels
● for loop - no parametrized for(;;)
● while - same as java
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
return if (isJvmRuntime) {
RuntimeEnvironment.application
} else {
InstrumentationRegistry.getContext()
}
● No goto
● return, break and continue can use labels
● for loop - no parametrized for(;;)
● while - same as java
● if - same as java, can be used as an expression
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
return when (isJvmRuntime) {
true -> RuntimeEnvironment.application
else -> InstrumentationRegistry.getContext()
}
● No goto
● return, break and continue can use labels
● for loop - no parametrized for(;;)
● while - same as java
● if - same as java, can be used as an expression
● when - replaces switch from java, can be used as expr.
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
val z = when {
x.isOdd() -> "x is odd"
y.isEven() -> "y is even"
else -> "x is funny, y is cool"
}
● No goto
● return, break and continue can use labels
● for loop - no parametrized for(;;)
● while - same as java
● if - same as java, can be used as an expression
● when - replaces switch from java, can be used as expr.
Control Flow
OBJECTS AND FLOW
y/kotlin-workbook
val isJvmRuntime = try {
Class.forName("org.robolectric.RuntimeEnvironment")
true
} catch (notFound: ClassNotFoundException) {
false
}
● No goto
● return, break and continue can use labels
● for loop - no parametrized for(;;)
● while - same as java
● if - same as java, can be used as an expression
● when - replaces switch from java, can be used as expr.
● try catch - same as java, can be used as an expression
Questions?
Next Up: Functions

More Related Content

What's hot

03 function overloading
03 function overloading03 function overloading
03 function overloading
Jasleen Kaur (Chandigarh University)
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
偉格 高
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator OverloadingHadziq Fabroyir
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading Charndeep Sekhon
 
3 Function Overloading
3 Function Overloading3 Function Overloading
3 Function Overloading
Praveen M Jigajinni
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
Ritika Sharma
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingabhay singh
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
ramya marichamy
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: FunctionsAdam Crabtree
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
Kamlesh Makvana
 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and Future
John De Goes
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
Romain Francois
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
Rai University
 
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
DevDay.org
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
Inline function
Inline functionInline function
Inline functionTech_MX
 

What's hot (20)

Lecture05
Lecture05Lecture05
Lecture05
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 
3 Function Overloading
3 Function Overloading3 Function Overloading
3 Function Overloading
 
Javascript ch6
Javascript ch6Javascript ch6
Javascript ch6
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and Future
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
 
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Compile time polymorphism
Compile time polymorphismCompile time polymorphism
Compile time polymorphism
 
Inline function
Inline functionInline function
Inline function
 

Similar to Kotlin For Android - Constructors and Control Flow (part 2 of 7)

Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)
Gesh Markov
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
VMware Tanzu
 
NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionNetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf Edition
Paulo Morgado
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
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
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
Squareboat
 
Bologna Developer Zone - About Kotlin
Bologna Developer Zone - About KotlinBologna Developer Zone - About Kotlin
Bologna Developer Zone - About Kotlin
Marco Vasapollo
 
Kotlin
KotlinKotlin
Kotlin
BoKaiRuan
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into Javascript
Massimo Franciosa
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
Minseo Chayabanjonglerd
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suckerockendude
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much more
Alin Pandichi
 
Kotlin for android developers whats new
Kotlin for android developers whats newKotlin for android developers whats new
Kotlin for android developers whats new
Serghii Chaban
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard Library
Nelson Glauber Leal
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
Francesco Usai
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
Daniel Eriksson
 
李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义yiditushe
 

Similar to Kotlin For Android - Constructors and Control Flow (part 2 of 7) (20)

Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)Kotlin For Android - Functions (part 3 of 7)
Kotlin For Android - Functions (part 3 of 7)
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionNetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf Edition
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
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
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Bologna Developer Zone - About Kotlin
Bologna Developer Zone - About KotlinBologna Developer Zone - About Kotlin
Bologna Developer Zone - About Kotlin
 
Kotlin
KotlinKotlin
Kotlin
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into Javascript
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much more
 
Kotlin for android developers whats new
Kotlin for android developers whats newKotlin for android developers whats new
Kotlin for android developers whats new
 
Mastering Kotlin Standard Library
Mastering Kotlin Standard LibraryMastering Kotlin Standard Library
Mastering Kotlin Standard Library
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
 
李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义李建忠、侯捷设计模式讲义
李建忠、侯捷设计模式讲义
 

Recently uploaded

Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 

Recently uploaded (20)

Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 

Kotlin For Android - Constructors and Control Flow (part 2 of 7)

  • 1. Kotlin for Android May 24, 2018 y/kotlin-workbook
  • 2. Objects, Constructors and Control Flow y/kotlin-workbook
  • 3. classes BASIC SYNTAX y/kotlin-workbook interface Runnable { fun run() } interface RepeatingRunnable : Runnable { fun run(times: Int) { (1..times).forEach { run() } } } open class Greeting : Runnable { override fun run() = println("Hi!") } class RepeatingGreeting : Greeting(), RepeatingRunnable RepeatingGreeting().run(3)
  • 4. ● One primary constructor as part of class declaration ○ Declare property visibility and default values in the parameter list constructors OBJECTS AND FLOW y/kotlin-workbook class Person( val name: String = "John", private var age: Int )
  • 5. ● One primary constructor as part of class declaration ○ Declare property visibility and default values in the parameter list ● Initialization blocks - init constructors OBJECTS AND FLOW y/kotlin-workbook class Person( val name: String = "John", private var age: Int ){ init { // Initialize things here... } }
  • 6. ● One primary constructor as part of class declaration ○ Declare property visibility and default values in the parameter list ● Initialization blocks - init ● Optional secondary constructors ● Property initialization constructors OBJECTS AND FLOW y/kotlin-workbook class Person( val name: String = "John", private var age: Int ){ var hairColor: Color = Color.BLACK init { // Initialize things here... } constructor(age: Int, hairColor: Color): this(age = age){ this.hairColor = hairColor } }
  • 8. object OBJECTS AND FLOW y/kotlin-workbook ● Used to create anonymous inner classes and singletons ● Can have static methods in the JVM ● Can have static fields in the JVM ● Every class can have a companion object ● Cannot inherit from object ○ object can inherit and extend though
  • 9. object OBJECTS AND FLOW y/kotlin-workbook object Foo { val BAR = "BAR" fun hi() = "hi" } // kotlin val bar = Foo.BAR val foo = Foo.hi() // java String bar = Foo.INSTANCE.BAR; String foo = Foo.INSTANCE.hi();
  • 10. object OBJECTS AND FLOW y/kotlin-workbook object Foo { const val BAR = "BAR" @JvmStatic fun hi() = "hi" } // kotlin val bar = Foo.BAR val foo = Foo.hi() // java String bar = Foo.INSTANCE.BAR; String foo = Foo.INSTANCE.hi(); // java improved interop String bar = Foo.BAR; String foo = Foo.hi();
  • 11. companion object advanced OBJECTS AND FLOW y/kotlin-workbook UserRepo.intance() // returns the real repo BizRepo.intance() // returns the real repo UserRepo.mock = mock(UserRepo) BizRepo.mock = mock(BizRepo) UserRepo.intance() // returns the mock repo BizRepo.intance() // returns the mock repo UserRepo.mock = null BizRepo.mock = null UserRepo.intance() // returns the real repo BizRepo.intance() // returns the real repo
  • 12. companion object advanced OBJECTS AND FLOW y/kotlin-workbook interface Factory<T: Any> { var mock: T? fun instance(): T } UserRepo.intance() // returns the real repo BizRepo.intance() // returns the real repo UserRepo.mock = mock(UserRepo) BizRepo.mock = mock(BizRepo) UserRepo.intance() // returns the mock repo BizRepo.intance() // returns the mock repo UserRepo.mock = null BizRepo.mock = null UserRepo.intance() // returns the real repo BizRepo.intance() // returns the real repo
  • 13. companion object advanced OBJECTS AND FLOW y/kotlin-workbook interface Factory<T: Any> { var mock: T? fun instance(): T } open class Provider<T: Any>(init: () -> T): Factory<T> { override var mock: T? = null private val instance: T by lazy(init) override fun instance() = mock ?: instance } UserRepo.intance() // returns the real repo BizRepo.intance() // returns the real repo UserRepo.mock = mock(UserRepo) BizRepo.mock = mock(BizRepo) UserRepo.intance() // returns the mock repo BizRepo.intance() // returns the mock repo UserRepo.mock = null BizRepo.mock = null UserRepo.intance() // returns the real repo BizRepo.intance() // returns the real repo
  • 14. companion object advanced OBJECTS AND FLOW y/kotlin-workbook interface Factory<T: Any> { var mock: T? fun instance(): T } open class Provider<T: Any>(init: () -> T): Factory<T> { override var mock: T? = null private val instance: T by lazy(init) override fun instance() = mock ?: instance } class UserRepo { companion object : Provider<UserRepo>({ UserRepo() }) } class BizRepo { companion object : Provider<BizRepo>({ BizRepo() }) } UserRepo.intance() // returns the real repo BizRepo.intance() // returns the real repo UserRepo.mock = mock(UserRepo) BizRepo.mock = mock(BizRepo) UserRepo.intance() // returns the mock repo BizRepo.intance() // returns the mock repo UserRepo.mock = null BizRepo.mock = null UserRepo.intance() // returns the real repo BizRepo.intance() // returns the real repo
  • 15. ● No goto Control Flow OBJECTS AND FLOW y/kotlin-workbook
  • 16. Control Flow OBJECTS AND FLOW y/kotlin-workbook fun foo() { listOf(1, 2, 3, 4, 5).forEach { if (it == 3) return print(it) } println(" this is unreachable") } ● No goto ● return, break and continue
  • 17. Control Flow OBJECTS AND FLOW y/kotlin-workbook fun foo() { listOf(1, 2, 3, 4, 5).forEach { if (it == 3) return print(it) } println(" this is unreachable") } // 12 ● No goto ● return, break and continue
  • 18. Control Flow OBJECTS AND FLOW y/kotlin-workbook fun foo() { listOf(1, 2, 3, 4, 5).forEach { if (it == 3) return@forEach print(it) } println(" this is reachable") } ● No goto ● return, break and continue can use labels
  • 19. Control Flow OBJECTS AND FLOW y/kotlin-workbook fun foo() { listOf(1, 2, 3, 4, 5).forEach { if (it == 3) return@forEach print(it) } println(" this is reachable") } // 1245 this is reachable ● No goto ● return, break and continue can use labels
  • 20. Control Flow OBJECTS AND FLOW y/kotlin-workbook fun foo() { listOf(1, 2, 3, 4, 5).forEach loop@{ if (it == 3) return@loop print(it) } println(" this is reachable") } // 1245 this is reachable ● No goto ● return, break and continue can use labels
  • 21. Control Flow OBJECTS AND FLOW y/kotlin-workbook fun foo() { listOf(1, 2, 3, 4, 5).run { forEach { if (it == 3) return@run print(it) }} println(" this is reachable") } // 12 this is reachable ● No goto ● return, break and continue can use labels
  • 22. Control Flow OBJECTS AND FLOW y/kotlin-workbook fun foo() { for (int in listOf(1, 2, 3, 4, 5)) { if (int == 3) break print(int) } println(" this is reachable") } ● No goto ● return, break and continue can use labels ● for loop - no parameterized for(;;)
  • 23. Control Flow OBJECTS AND FLOW y/kotlin-workbook ● No goto ● return, break and continue can use labels ● for loop - no parametrized for(;;) ● while - same as java
  • 24. Control Flow OBJECTS AND FLOW y/kotlin-workbook return if (isJvmRuntime) { RuntimeEnvironment.application } else { InstrumentationRegistry.getContext() } ● No goto ● return, break and continue can use labels ● for loop - no parametrized for(;;) ● while - same as java ● if - same as java, can be used as an expression
  • 25. Control Flow OBJECTS AND FLOW y/kotlin-workbook return when (isJvmRuntime) { true -> RuntimeEnvironment.application else -> InstrumentationRegistry.getContext() } ● No goto ● return, break and continue can use labels ● for loop - no parametrized for(;;) ● while - same as java ● if - same as java, can be used as an expression ● when - replaces switch from java, can be used as expr.
  • 26. Control Flow OBJECTS AND FLOW y/kotlin-workbook val z = when { x.isOdd() -> "x is odd" y.isEven() -> "y is even" else -> "x is funny, y is cool" } ● No goto ● return, break and continue can use labels ● for loop - no parametrized for(;;) ● while - same as java ● if - same as java, can be used as an expression ● when - replaces switch from java, can be used as expr.
  • 27. Control Flow OBJECTS AND FLOW y/kotlin-workbook val isJvmRuntime = try { Class.forName("org.robolectric.RuntimeEnvironment") true } catch (notFound: ClassNotFoundException) { false } ● No goto ● return, break and continue can use labels ● for loop - no parametrized for(;;) ● while - same as java ● if - same as java, can be used as an expression ● when - replaces switch from java, can be used as expr. ● try catch - same as java, can be used as an expression

Editor's Notes

  1. Continue where we left off - deep dive on constructors
  2. Any number of init blocks Nonnull properties outside the primary constructor must be initialized by the end of the block
  3. Secondary constructors must delegate to primary constructor if declared
  4. Deep dive on constructors
  5. Anonymous inner class is an object expression, singleton is an object declaration Is as close to having static as kotlin allows still instance members of real objects
  6. Kotlin looks just like you remember with java statics Not super friendly interop
  7. Return real repo only if mock is not set Painful to do in Java without inheritance, must implement for both
  8. Talk about generics Most permissive generic is Any?
  9. Called local return, uses an implicit label This return is equivalent to a continue, and only 3 will not be printed
  10. Called local return, uses an implicit label This return is equivalent to a continue, and only 3 will not be printed
  11. Can explicitly declare the labels Same as above slide
  12. Can use .withIndex() and destructure: for ((index, value) in array.withIndex())
  13. Compiles down to if/else blocks Only need else in expression and if you use enums/sealed class it isn’t needed No fall through
  14. Not parameterized evaluates each and evaluates first true Can use blocks of code
  15. ALMOST END OF SLIDES - NEXT SLIDE IS LAST - Q&A STARTS