SlideShare a Scribd company logo
1 of 24
Kotlin for Android
May 24, 2018
y/kotlin-workbook
Properties, Annotations and Nullability
y/kotlin-workbook
Kotlin Properties
PROPERTIES
interface Factory<T: Any> {
var mock: T?
}
class Provider<T: Any>(init: () -> T): Factory<T> {
override var mock: T? = null
val instance: T by lazy(init)
}
provider.mock = mock(...)
y/kotlin-workbook
● Properties replace java fields
● Declared in primary constructor or at the top of a class
● Declaration is like variables inside a function
● Can be declared inside interfaces
Kotlin Properties
PROPERTIES
interface Factory<T: Any> {
var mock: T?
}
class Provider<T: Any>(init: () -> T): Factory<T> {
override var mock: T? = null
val instance: T by lazy(init)
private set
}
provider.mock = mock(...)
y/kotlin-workbook
● Properties replace java fields
● Declaration is like variables inside a type
● Can be declared inside interfaces
● Properties compile into:
○ A field + getter for val
○ A field + getter & setter for var
○ The field is private
○ Getter has same visibility
○ Setter defaults to same visibility
private final String string;
String getString() // Java getter
val string: String // Kotlin val
private CharSequence text;
CharSequence getText() // Java getter
void setText(CharSequence sss) // Java setter
var text: CharSequence // Kotlin var
private Boolean isMarried;
Boolean isMarried() // Java getter
void setMarried(Boolean married) // Java setter
var isMarried: Boolean // Kotlin var
Java Synthetic
Properties
PROPERTIES
y/kotlin-workbook
Kotlin Properties
PROPERTIES
interface Factory<T: Any> {
var mock: T?
}
class Provider<T: Any>(init: () -> T): Factory<T> {
override var mock: T? = null
@get:JvmName("it")
val instance: T by lazy(init)
private set
}
provider.mock = mock(...)
y/kotlin-workbook
● Properties replace java fields
● Declaration is like variables inside a type
● Can be declared inside interfaces
● Properties compile into several members
● Use qualifiers to annotate a part of a property
Annotation Qualifiers
PROPERTIES
y/kotlin-workbook
Qualifier @Foo applies to
@file:Foo Entire .kt file
@param:Foo Parameter of a single-param fun
@receiver:Foo Receiver of a fun with receiver
Below are exclusive or most relevant to properties
@property:Foo The property ¯_(ツ)_/¯
@field:Foo Field of a property
@get:Foo Getter of a property
@set:Foo Setter of a property
@setparam:Foo The parameter of the setter of a property
@delegate:Foo The delegate of a property
// Suppress unused warnings in the file
@file:Suppress("unused")
// Get a string through context
fun @receiver:StringRes Int.getString() = …
class Example(
// annotate Java field
@field:DrawableRes val foo: Int,
// annotate Java getter
@get:VisibleForTesting val bar: Boolean,
// annotate Java constructor parameter
@param:Mock val quux)
Annotation Qualifiers
PROPERTIES
y/kotlin-workbook
● Delegate the implementation of a property
● Has to implement getValue() for val
● Additionally setValue() for var
Property Delegates
PROPERTIES
y/kotlin-workbook
Property Delegates
PROPERTIES
interface Delegate<T> {
operator fun getValue(
thisRef: Any?,
property: KProperty<T>): T
operator fun setValue(
thisRef: Any?,
property: KProperty<T>,
value: T)
}
y/kotlin-workbook
● Delegate the implementation of a property
● Has to implement getValue() for val
● Additionally setValue() for var
class C {
var p: T by MyDelegate()
}
// Compiles down to:
class C {
private val p$delegate = MyDelegate()
var p: T
get() = p$delegate.getValue(this, this::p)
set(v: T) = p$delegate.setValue(this, this::p, v)
}
Property Delegates
PROPERTIES
y/kotlin-workbook
class Foo {
val foo: String by lazy { "moo" }
val bar: Int by lazy { 5 }
}
Property Delegates
PROPERTIES
y/kotlin-workbook
open class BackedByMap {
protected val _map = mutableMapOf<String, Any?>()
}
class Foo : BackedByMap() {
var foo: String? by _map
var bar: Int? by _map
}
Property Delegates
Magic
PROPERTIES
y/kotlin-workbook
open class BackedByMap {
protected val _map = mutableMapOf<String, Any?>()
}
class Foo : BackedByMap() {
var foo: String? by _map
var bar: Int? by _map
}
class User(val map: Map<String, Any?>) {
val name: String by map
val age: Int by map
}
Property Delegates
Magic
PROPERTIES
y/kotlin-workbook
Property Delegates
Magic
PROPERTIES
open class BackedByMap {
protected val _map = mutableMapOf<String, Any?>()
}
class Foo : BackedByMap() {
var foo: String? by _map
var bar: Int? by _map
}
val f = Foo()
f.foo = "moo"
f.bar = 5
y/kotlin-workbook
Property Delegates
Magic
PROPERTIES
open class BackedByMap {
protected val _map = mutableMapOf<String, Any?>()
val map get() = _map.toMap()
}
class Foo : BackedByMap() {
var foo: String? by _map
var bar: Int? by _map
}
val f = Foo()
println(f.map) // {}
f.foo = "moo"
f.bar = 5
println(f.map) // {foo=moo, bar=5}
f.foo = null
println(f.map) // {foo=null, bar=5}
f.bar = null
println(f.map) // {foo=null, bar=null}
y/kotlin-workbook
Property Delegates
Magic
PROPERTIES
open class BackedByMap {
protected val _map = mutableMapOf<String, Any?>()
val map get() = _map.filterValues { it != null }
}
class Foo : BackedByMap() {
var foo: String? by _map
var bar: Int? by _map
}
val f = Foo()
println(f.map) // {}
f.foo = "moo"
f.bar = 5
println(f.map) // {foo=moo, bar=5}
f.foo = null
println(f.map) // {bar=5}
f.bar = null
println(f.map) // {}
y/kotlin-workbook
● Kind of like lazy
● Limited to var
● No additional code
● Compiler will not check and may crash at runtime
● Only makes sense for non-null properties
lateinit
PROPERTIES
y/kotlin-workbook
● Every type has a nullable version
○ Any vs Any?Nullability
PROPERTIES
y/kotlin-workbook
Nullability
PROPERTIES
val any: Any = Any()
val maybe: Any? = null
fun show(maybe: Any?) = print(maybe)
fun reallyShow(any: Any) = print(any)
show(maybe)
show(any)
reallyShow(any)
reallyShow(maybe) // compiler error
maybe?.let(::reallyShow) // Coming Soon™
y/kotlin-workbook
● Every type has a nullable version - Any?
● Can supply non-nullable argument to a nullable
parameter
○ Vice-versa is a compiler error
Nullability
PROPERTIES
val maybe: Any? = null
maybe.hashCode() // Compiler error
maybe?.hashCode() // OK
maybe?.hashCode().compareTo(42) // Compiler error
maybe?.hashCode()?.compareTo(42) // OK
if (maybe != null) {
maybe.hashCode() // Compiler knows value is nonnull
}y/kotlin-workbook
● Every type has a nullable version - Any?
● Can supply non-nullable argument to a nullable
parameter
● Safe invocation
Nullability
PROPERTIES
val maybe: Any? = null
fun Any?.hashCode() = this?.hashCode() ?: 0
maybe.hashCode() // OK
maybe.hashCode().compareTo(42) // OK
y/kotlin-workbook
● Every type has a nullable version - Any?
● Can supply non-nullable argument to a nullable
parameter
● Safe invocation
● You can extend nullable types
Nullability
PROPERTIES
val any: Any = Any()
val maybe: Any? = null
fun Any?.hashCode() = this?.hashCode() ?: 0
maybe.hashCode() // OK
any.hashCode() // OK
maybe.hashCode().compareTo(42) // OK
y/kotlin-workbook
● Every type has a nullable version - Any?
● Can supply non-nullable argument to a nullable
parameter
● Safe invocation
● You can extend nullable types
Questions?
Next Up: Extension Functions in kotlin-std-lib

More Related Content

What's hot

Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
 
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
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKamal Acharya
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingfarhan amjad
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++Ilio Catallo
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading Charndeep Sekhon
 
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)Gesh Markov
 
C++ overloading
C++ overloadingC++ overloading
C++ overloadingsanya6900
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++PRINCE KUMAR
 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)MoonSheikh1
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Yaksh Jethva
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?Federico Tomassetti
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpprajshreemuthiah
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
Function different types of funtion
Function different types of funtionFunction different types of funtion
Function different types of funtionsvishalsingh01
 
Inline function
Inline functionInline function
Inline functionTech_MX
 

What's hot (20)

Operator overloading
Operator overloading Operator overloading
Operator overloading
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
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++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++
 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Function different types of funtion
Function different types of funtionFunction different types of funtion
Function different types of funtion
 
Inline function
Inline functionInline function
Inline function
 

Similar to Kotlin For Android - Properties (part 4 of 7)

Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)Gesh Markov
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
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
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlinvriddhigupta
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developersMohamed Wael
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does notSergey Bandysik
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
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
 
Swift Programming
Swift ProgrammingSwift Programming
Swift ProgrammingCodemotion
 
TMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart CastsTMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart CastsIosif Itkin
 
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdfAndrey Breslav
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyHaim Yadid
 
Save time with kotlin in android development
Save time with kotlin in android developmentSave time with kotlin in android development
Save time with kotlin in android developmentAdit Lal
 

Similar to Kotlin For Android - Properties (part 4 of 7) (20)

Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
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)
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does not
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro 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...
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Swift, swiftly
Swift, swiftlySwift, swiftly
Swift, swiftly
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Swift Programming
Swift ProgrammingSwift Programming
Swift Programming
 
TMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart CastsTMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart Casts
 
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, Seriously
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Save time with kotlin in android development
Save time with kotlin in android developmentSave time with kotlin in android development
Save time with kotlin in android development
 

Recently uploaded

%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 

Recently uploaded (20)

%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 

Kotlin For Android - Properties (part 4 of 7)

  • 1. Kotlin for Android May 24, 2018 y/kotlin-workbook
  • 2. Properties, Annotations and Nullability y/kotlin-workbook
  • 3. Kotlin Properties PROPERTIES interface Factory<T: Any> { var mock: T? } class Provider<T: Any>(init: () -> T): Factory<T> { override var mock: T? = null val instance: T by lazy(init) } provider.mock = mock(...) y/kotlin-workbook ● Properties replace java fields ● Declared in primary constructor or at the top of a class ● Declaration is like variables inside a function ● Can be declared inside interfaces
  • 4. Kotlin Properties PROPERTIES interface Factory<T: Any> { var mock: T? } class Provider<T: Any>(init: () -> T): Factory<T> { override var mock: T? = null val instance: T by lazy(init) private set } provider.mock = mock(...) y/kotlin-workbook ● Properties replace java fields ● Declaration is like variables inside a type ● Can be declared inside interfaces ● Properties compile into: ○ A field + getter for val ○ A field + getter & setter for var ○ The field is private ○ Getter has same visibility ○ Setter defaults to same visibility
  • 5. private final String string; String getString() // Java getter val string: String // Kotlin val private CharSequence text; CharSequence getText() // Java getter void setText(CharSequence sss) // Java setter var text: CharSequence // Kotlin var private Boolean isMarried; Boolean isMarried() // Java getter void setMarried(Boolean married) // Java setter var isMarried: Boolean // Kotlin var Java Synthetic Properties PROPERTIES y/kotlin-workbook
  • 6. Kotlin Properties PROPERTIES interface Factory<T: Any> { var mock: T? } class Provider<T: Any>(init: () -> T): Factory<T> { override var mock: T? = null @get:JvmName("it") val instance: T by lazy(init) private set } provider.mock = mock(...) y/kotlin-workbook ● Properties replace java fields ● Declaration is like variables inside a type ● Can be declared inside interfaces ● Properties compile into several members ● Use qualifiers to annotate a part of a property
  • 7. Annotation Qualifiers PROPERTIES y/kotlin-workbook Qualifier @Foo applies to @file:Foo Entire .kt file @param:Foo Parameter of a single-param fun @receiver:Foo Receiver of a fun with receiver Below are exclusive or most relevant to properties @property:Foo The property ¯_(ツ)_/¯ @field:Foo Field of a property @get:Foo Getter of a property @set:Foo Setter of a property @setparam:Foo The parameter of the setter of a property @delegate:Foo The delegate of a property
  • 8. // Suppress unused warnings in the file @file:Suppress("unused") // Get a string through context fun @receiver:StringRes Int.getString() = … class Example( // annotate Java field @field:DrawableRes val foo: Int, // annotate Java getter @get:VisibleForTesting val bar: Boolean, // annotate Java constructor parameter @param:Mock val quux) Annotation Qualifiers PROPERTIES y/kotlin-workbook
  • 9. ● Delegate the implementation of a property ● Has to implement getValue() for val ● Additionally setValue() for var Property Delegates PROPERTIES y/kotlin-workbook
  • 10. Property Delegates PROPERTIES interface Delegate<T> { operator fun getValue( thisRef: Any?, property: KProperty<T>): T operator fun setValue( thisRef: Any?, property: KProperty<T>, value: T) } y/kotlin-workbook ● Delegate the implementation of a property ● Has to implement getValue() for val ● Additionally setValue() for var
  • 11. class C { var p: T by MyDelegate() } // Compiles down to: class C { private val p$delegate = MyDelegate() var p: T get() = p$delegate.getValue(this, this::p) set(v: T) = p$delegate.setValue(this, this::p, v) } Property Delegates PROPERTIES y/kotlin-workbook
  • 12. class Foo { val foo: String by lazy { "moo" } val bar: Int by lazy { 5 } } Property Delegates PROPERTIES y/kotlin-workbook
  • 13. open class BackedByMap { protected val _map = mutableMapOf<String, Any?>() } class Foo : BackedByMap() { var foo: String? by _map var bar: Int? by _map } Property Delegates Magic PROPERTIES y/kotlin-workbook
  • 14. open class BackedByMap { protected val _map = mutableMapOf<String, Any?>() } class Foo : BackedByMap() { var foo: String? by _map var bar: Int? by _map } class User(val map: Map<String, Any?>) { val name: String by map val age: Int by map } Property Delegates Magic PROPERTIES y/kotlin-workbook
  • 15. Property Delegates Magic PROPERTIES open class BackedByMap { protected val _map = mutableMapOf<String, Any?>() } class Foo : BackedByMap() { var foo: String? by _map var bar: Int? by _map } val f = Foo() f.foo = "moo" f.bar = 5 y/kotlin-workbook
  • 16. Property Delegates Magic PROPERTIES open class BackedByMap { protected val _map = mutableMapOf<String, Any?>() val map get() = _map.toMap() } class Foo : BackedByMap() { var foo: String? by _map var bar: Int? by _map } val f = Foo() println(f.map) // {} f.foo = "moo" f.bar = 5 println(f.map) // {foo=moo, bar=5} f.foo = null println(f.map) // {foo=null, bar=5} f.bar = null println(f.map) // {foo=null, bar=null} y/kotlin-workbook
  • 17. Property Delegates Magic PROPERTIES open class BackedByMap { protected val _map = mutableMapOf<String, Any?>() val map get() = _map.filterValues { it != null } } class Foo : BackedByMap() { var foo: String? by _map var bar: Int? by _map } val f = Foo() println(f.map) // {} f.foo = "moo" f.bar = 5 println(f.map) // {foo=moo, bar=5} f.foo = null println(f.map) // {bar=5} f.bar = null println(f.map) // {} y/kotlin-workbook
  • 18. ● Kind of like lazy ● Limited to var ● No additional code ● Compiler will not check and may crash at runtime ● Only makes sense for non-null properties lateinit PROPERTIES y/kotlin-workbook
  • 19. ● Every type has a nullable version ○ Any vs Any?Nullability PROPERTIES y/kotlin-workbook
  • 20. Nullability PROPERTIES val any: Any = Any() val maybe: Any? = null fun show(maybe: Any?) = print(maybe) fun reallyShow(any: Any) = print(any) show(maybe) show(any) reallyShow(any) reallyShow(maybe) // compiler error maybe?.let(::reallyShow) // Coming Soon™ y/kotlin-workbook ● Every type has a nullable version - Any? ● Can supply non-nullable argument to a nullable parameter ○ Vice-versa is a compiler error
  • 21. Nullability PROPERTIES val maybe: Any? = null maybe.hashCode() // Compiler error maybe?.hashCode() // OK maybe?.hashCode().compareTo(42) // Compiler error maybe?.hashCode()?.compareTo(42) // OK if (maybe != null) { maybe.hashCode() // Compiler knows value is nonnull }y/kotlin-workbook ● Every type has a nullable version - Any? ● Can supply non-nullable argument to a nullable parameter ● Safe invocation
  • 22. Nullability PROPERTIES val maybe: Any? = null fun Any?.hashCode() = this?.hashCode() ?: 0 maybe.hashCode() // OK maybe.hashCode().compareTo(42) // OK y/kotlin-workbook ● Every type has a nullable version - Any? ● Can supply non-nullable argument to a nullable parameter ● Safe invocation ● You can extend nullable types
  • 23. Nullability PROPERTIES val any: Any = Any() val maybe: Any? = null fun Any?.hashCode() = this?.hashCode() ?: 0 maybe.hashCode() // OK any.hashCode() // OK maybe.hashCode().compareTo(42) // OK y/kotlin-workbook ● Every type has a nullable version - Any? ● Can supply non-nullable argument to a nullable parameter ● Safe invocation ● You can extend nullable types
  • 24. Questions? Next Up: Extension Functions in kotlin-std-lib

Editor's Notes

  1. Talk about non-nullable annotations and their nullable counter-parts We’ll talk more about nullability itself later
  2. Additional overloads don’t matter isFoo() and setFoo()
  3. Talk about custom implementations for get() and set() If you do not access the generated field via the keyword field the compiler will not generate it Properties like that are generally referred to as virtual or synthetic
  4. Most common delegate from std-lib - lazy In case we don’t come up with better example mention that this is a bad use case and can be replaced with assignment
  5. ALMOST END OF SLIDES - NEXT SLIDE IS LAST - Q&A STARTS