SlideShare a Scribd company logo
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

PPTX
Firebase Remote Config + Kotlin = EasyFRC
PPTX
Polymorphismupload
PDF
Functional go
PDF
Kotlin, smarter development for the jvm
PPTX
Function overloading and overriding
PPTX
Getting Started With Kotlin
PPTX
Pure virtual function and abstract class
PDF
A quick and fast intro to Kotlin
Firebase Remote Config + Kotlin = EasyFRC
Polymorphismupload
Functional go
Kotlin, smarter development for the jvm
Function overloading and overriding
Getting Started With Kotlin
Pure virtual function and abstract class
A quick and fast intro to Kotlin

What's hot (20)

PPT
Operator overloading
PDF
Kotlin cheat sheet by ekito
PPT
14 operator overloading
PPTX
Function overloading
PPTX
operator overloading & type conversion in cpp over view || c++
PDF
Operator overloading
PPT
Operator overloading
PDF
Operator overloading in C++
PPTX
Presentation on overloading
PPTX
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
PPT
C++ overloading
PPTX
Polymorphism Using C++
PPTX
Virtual function complete By Abdul Wahab (moon sheikh)
PDF
Operator_Overloaing_Type_Conversion_OOPC(C++)
PDF
How do you create a programming language for the JVM?
PPTX
Operator overloading and type conversion in cpp
KEY
Exciting JavaScript - Part I
PPTX
Operator overloading
PPTX
Function different types of funtion
PPTX
Inline function
Operator overloading
Kotlin cheat sheet by ekito
14 operator overloading
Function overloading
operator overloading & type conversion in cpp over view || c++
Operator overloading
Operator overloading
Operator overloading in C++
Presentation on overloading
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
C++ overloading
Polymorphism Using C++
Virtual function complete By Abdul Wahab (moon sheikh)
Operator_Overloaing_Type_Conversion_OOPC(C++)
How do you create a programming language for the JVM?
Operator overloading and type conversion in cpp
Exciting JavaScript - Part I
Operator overloading
Function different types of funtion
Inline function
Ad

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

PDF
2 kotlin vs. java: what java has that kotlin does not
PDF
Kotlin for Android Developers - 3
PDF
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
PDF
Exploring Kotlin
PDF
Kotlin for Android devs
PPTX
Kotlin For Android - Basics (part 1 of 7)
PDF
Intro to Kotlin
PDF
Privet Kotlin (Windy City DevFest)
PDF
Kotlin killed Java stars
PDF
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
PDF
Kotlin Developer Starter in Android projects
PPTX
Kotlin in action
PDF
Kotlin Austin Droids April 14 2016
PDF
Kotlin on Android: Delegate with pleasure
PDF
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
PPTX
Kotlin as a Better Java
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
PDF
Kotlin intro
PPTX
Introduction to Koltin for Android Part I
2 kotlin vs. java: what java has that kotlin does not
Kotlin for Android Developers - 3
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Exploring Kotlin
Kotlin for Android devs
Kotlin For Android - Basics (part 1 of 7)
Intro to Kotlin
Privet Kotlin (Windy City DevFest)
Kotlin killed Java stars
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android projects
Kotlin in action
Kotlin Austin Droids April 14 2016
Kotlin on Android: Delegate with pleasure
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Kotlin as a Better Java
Develop your next app with kotlin @ AndroidMakersFr 2017
Kotlin intro
Introduction to Koltin for Android Part I
Ad

Recently uploaded (20)

PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
history of c programming in notes for students .pptx
PPTX
Computer Software and OS of computer science of grade 11.pptx
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
assetexplorer- product-overview - presentation
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
ai tools demonstartion for schools and inter college
PDF
Nekopoi APK 2025 free lastest update
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPT
Introduction Database Management System for Course Database
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Design an Analysis of Algorithms I-SECS-1021-03
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Design an Analysis of Algorithms II-SECS-1021-03
history of c programming in notes for students .pptx
Computer Software and OS of computer science of grade 11.pptx
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
VVF-Customer-Presentation2025-Ver1.9.pptx
assetexplorer- product-overview - presentation
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
ai tools demonstartion for schools and inter college
Nekopoi APK 2025 free lastest update
Reimagine Home Health with the Power of Agentic AI​
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
How to Migrate SBCGlobal Email to Yahoo Easily
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Introduction Database Management System for Course Database
Operating system designcfffgfgggggggvggggggggg
Design an Analysis of Algorithms I-SECS-1021-03

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

  • #4: Talk about non-nullable annotations and their nullable counter-parts We’ll talk more about nullability itself later
  • #6: Additional overloads don’t matter isFoo() and setFoo()
  • #12: 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
  • #13: 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
  • #24: ALMOST END OF SLIDES - NEXT SLIDE IS LAST - Q&A STARTS