SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Sinan Kozak @snnkzkFebruary 20th, 2020
Kotlin
Delegation
Page @snnkzk
In software engineering, the delegation pattern is an object-oriented
design pattern that allows object composition to achieve the same
code reuse as an inheritance.
(https://en.wikipedia.org/wiki/Delegation_pattern)
1
Page @snnkzk
– Property delegation
– Implementation delegation
Kotlin Delegation Features
2
Page
– Manually implemented logic inside get/set methods
– Code duplication
– Hard to test every usage
@snnkzk
Without Property Delegation
3
Page @snnkzk
Logic in get method
private var _name: String? = null
fun getName(): String {
if (_name == null) {
_name = ”Sinan"
}
return _name!!
}
4
Page @snnkzk
Logic in get method
private var _name: String? = null
fun getName(): String {
if (_name == null) {
_name = ”Sinan"
}
return _name!!
}
val name: String by lazy { "Sinan" }
5
Page @snnkzk
– Need nullable private backing field
– Code duplication for every new field
– Backing field is useable in same class
@snnkzk
Logic in get method for object creation
private var _name: String? = null
fun getName(): String {
if (_name == null) {
_name = ”Sinan"
}
return _name!!
}
6
Page @snnkzk
– A helper from Kotlin standard library
– An interface with a value object
– Run function when property is used
– “lazy() is a function that takes a
lambda and returns an instance
of Lazy<T> which can serve as a
delegate for implementing a lazy
property: the first call to get()
executes the lambda passed to
lazy() and remembers the result,
subsequent calls to get() simply
return the remembered result.”
What is lazy?
7
Page
– Language word for delegation
– For delegation property, there are two interfaces
• ReadWriteProperty
• ReadOnlyProperty
– For implementation delegation it expectes `interface by instance`
@snnkzk
What is ‘by’?
8
Page
– Really similar to lazy
– Creates a new view model and caches it
– Custom view model factory can be passed
@snnkzk
by viewModels() from AndroidX
9
Page
– Really similar to lazy
– Creates a new view model and caches it
– Custom view model factory can be passed
@snnkzk
by viewModels() from AndroidX
10
val model: MyViewModel by viewModels()
Page
– It is possible to create delegation depending on other types
– Instance will be passed as ref
– @AskAshDavies will write about it, maybe even a library
@snnkzk
Custom Examples
private var SharedPreferences.somePref: String by
sharedPreferencesStringOrDefault(”default value")
11
Page @snnkzk
Implementation Delegation
12
Page
– Delegate interface to different instance
– Prevent Code duplication
– Helps to contain logic as unit
– Compiler rewrite our classes with delegation
@snnkzk
Implementation Delegation
13
Page
– import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class JavaDelegatedList<T> implements List<T> {
private final List<T> innerList;
private int addCount = 0;
public JavaDelegatedList(List<T> innerList) {
this.innerList = innerList;
}
@Override
public int size() {
return innerList.size();
}
@Override
public boolean isEmpty() {
return innerList.isEmpty();
}
@Override
public boolean contains(Object o) {
return innerList.contains(o);
}
@Override
public Iterator<T> iterator() {
return innerList.iterator();
}
@snnkzk
Java Delegation
@Override
public Object[] toArray() {
return innerList.toArray();
}
@Override
public boolean add(T o) {
addCount++;
return innerList.add(o);
}
@Override
public boolean remove(Object o) {
return innerList.remove(o);
}
@Override
public boolean addAll(Collection c) {
addCount += c.size();
return innerList.addAll(c);
}
@Override
public boolean addAll(int index, Collection c) {
addCount += c.size();
return innerList.addAll(index, c);
}
@Override
public void clear() {
innerList.clear();
}
@Override
public T get(int index) {
return innerList.get(index);
}
@Override
public T set(int index, T element) {
return innerList.set(index, element);
}
@Override
public void add(int index, T element) {
addCount++;
innerList.add(index, element);
}
@Override
public T remove(int index) {
return innerList.remove(index);
}
@Override
public int indexOf(Object o) {
return innerList.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return innerList.lastIndexOf(o);
}
@Override
public ListIterator<T> listIterator() {
return innerList.listIterator();
}
@Override
public ListIterator<T> listIterator(int index) {
return innerList.listIterator(index);
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
return innerList.subList(fromIndex, toIndex);
}
@Override
public boolean retainAll(Collection c) {
return false;
}
@Override
public boolean removeAll(Collection c) {
return false;
}
@Override
public boolean containsAll(Collection c) {
return false;
}
@Override
public <T> T[] toArray(T[] a) {
return innerList.toArray(a);
}
}
14
Page @snnkzk
Implementation Delegation
class KotlinDelegateList(private val innerList: List<String>) :
List<String> by innerList
15
Page
– That is what they thought us 🤔
– We also learned why. Thanks Android
– Activities and Fragments forces us to use inheritance
@snnkzk
Favour composition over inheritance
16
Page
– That is what they thought us 🤔
– We also learned why. Thanks Android
– Activities and Fragments forces us to use inheritance
– Jean-Michel Fayard https://dev.to/jmfayard/android-s-billion-dollar-mistake-327b
@snnkzk
Favour composition over inheritance
17
Page @snnkzk
– Classes are final by default
Why is Kotlin different
18
Page @snnkzk
– Classes are final by default
– Data classes cannot be open
– You can inherit a data class from
a non-data class. Inheriting a
data class from another data
class is not allowed because
there is no way to make compiler-
generated data class methods
work consistently and intuitively
in case of inheritance. (Answer
from JetBrain team)
Why is Kotlin different
19
Page @snnkzk
interface ClosedShape {
fun area(): Int
}
class Rectangle(val width: Int, val height: Int) : ClosedShape {
override fun area() = width * height
}
class Circle(val radius: Int): ClosedShape {
override fun area(): Int = (Math.PI * radius * radius).toInt()
}
// We can have circle or rectangle window
class Window(private val bounds: ClosedShape) : ClosedShape by bounds
20
Page
– Need water, milk and espresso
– All have volume, name and price
– Any product needs to have invoice
@snnkzk
Coffee Shop Program Example
21
Page @snnkzk
Coffee Shop Program Example
data class Water(
override val name: String,
override val volume: Double,
override val cost: Double = volume * 0.0
) : Beverage
22
Page @snnkzk
Coffee Shop Program Example
data class Water(
override val name: String,
override val volume: Double,
override val cost: Double = volume * 0.0
) : Beverage
data class HotWater(override val volume: Double) :
Beverage by Water(name = "Hot water", volume = volume)
data class ColdWater(override val volume: Double) :
Beverage by Water(name = "Cold water", volume = volume)
23
Page @snnkzk
Coffee Shop Program Example
data class Milk(
override val name: String,
override val volume: Double,
override val cost: Double = volume * 1
) : Beverage
24
Page @snnkzk
Coffee Shop Program Example
data class Milk(
override val name: String,
override val volume: Double,
override val cost: Double = volume * 1
) : Beverage
data class HotMilk(override val volume: Double) :
Beverage by Milk(name = "Hot milk", volume = volume)
data class ColdMilk(override val volume: Double) :
Beverage by Milk(name = "Cold milk", volume = volume)
25
Page @snnkzk
Coffee Shop Program Example
data class Espresso(
override val volume: Double = 1.0,
private val base: Beverage = HotWater(volume)
) : Beverage by base {
override val name: String = "Espresso"
override val cost: Double = base.cost + volume * 3
}
26
Page
– We have base beverages water, milk and espresso
– We can create an extension function for plus operation
– End result of plus will be final product
– data class CombinedBeverage
@snnkzk
Coffee Shop Program Example
27
Page @snnkzk
Coffee Shop Program Example
data class Coffee(override val name: String = "Coffee") :
Beverage by Espresso() + HotWater(volume = 2.0)
data class ColdCoffee(override val name: String = "Cold coffee") :
Beverage by Espresso() + ColdWater(volume = 2.0)
data class HotMilkCoffee(override val name: String = "Hot Milk Coffee") :
Beverage by Espresso() + HotMilk(volume = 2.0)
data class ColdMilkCoffee(override val name: String = "Cold Milk Coffee") :
Beverage by Espresso() + ColdMilk(volume = 2.0)
data class DoubleMilkCoffee(override val name: String = "DoubleMilkCoffee") :
Beverage by Espresso() + HotMilk(volume = 4.0)
28
Page @snnkzk
– println("Espresso = ${Espresso().invoice()}")
// Espresso = 1.0 cc Hot water costs 0.0
– println("Coffee = ${Coffee().invoice()}")
// Coffee = 3.0 cc Espresso + Hot water costs 3.0
– println("ColdCoffee = ${ColdCoffee().invoice()}")
// ColdCoffee = 3.0 cc Espresso + Cold water costs 3.0
– println("HotMilkCoffee = ${HotMilkCoffee().invoice()}")
// HotMilkCoffee = 3.0 cc Espresso + Hot milk costs 5.0
– println("ColdMilkCoffee = ${ColdMilkCoffee().invoice()}")
// ColdMilkCoffee = 3.0 cc Espresso + Cold milk costs 5.0
– println("DoubleMilkCoffee = ${DoubleMilkCoffee().invoice()}")
// DoubleMilkCoffee = 5.0 cc Espresso + Hot milk costs 7.0
Invoice calls
Coffee Shop
Program Example
29
Page
– Be careful with ‘this’ usage
– return this
– ‘this’ always aims the class it is in
@snnkzk
Scoped ‘this’
30
Page @snnkzk
Scoped ‘this’
interface Beverage {
val volume: Double
val cost: Double
val name: String
fun invoice(): String = "$volume cc $name costs $cost"
fun returnThis(): Beverage
}
31
Page @snnkzk
Scoped ‘this’
data class Water(
override val name: String,
override val volume: Double,
override val cost: Double = volume * 0.0
) : Beverage {
override fun returnThis(): Beverage = this
}
data class Milk(
override val name: String,
override val volume: Double,
override val cost: Double = volume * 1
) : Beverage {
override fun returnThis(): Beverage = this
}
data class Espresso(
override val volume: Double = 1.0,
private val base: Beverage = HotWater(volume)
) : Beverage by base {
override val name: String = "Espresso"
override val cost: Double = base.cost + volume * 3
}
32
Page @snnkzk
Scoped ‘this’
println(”Espresso = ${Espresso().returnThis()}")
33
Page @snnkzk
Espresso = Water(name=Hot water, volume=1.0,
cost=0.0)
Scoped ‘this’
println(”Espresso = ${Espresso().returnThis()}")
data class Espresso(
override val volume: Double = 1.0,
private val base: Beverage
) : Beverage by base {
override val name: String = "Espresso
override val cost: Double = …
}
34
Page
– Extension on interface works for every class
– Extension override is possible
– Casting is required for using overridden extension
@snnkzk
Extension function parent class vs child class
35
Page
Thank you for
your attention.
Questions?
Sinan Kozak
@snnkzk
@snnkzk36

Weitere ähnliche Inhalte

Was ist angesagt?

Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickHermann Hueck
 
Cutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryCutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryWilliam Candillon
 
Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? DataWorks Summit
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Rebecca Grenier
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
Spark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSpark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSigmoid
 
SQL to Hive Cheat Sheet
SQL to Hive Cheat SheetSQL to Hive Cheat Sheet
SQL to Hive Cheat SheetHortonworks
 
Scalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/CascadingScalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/Cascadingjohnynek
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xqueryAmol Pujari
 
Building data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyBuilding data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyRoger Barnes
 
Writing Hadoop Jobs in Scala using Scalding
Writing Hadoop Jobs in Scala using ScaldingWriting Hadoop Jobs in Scala using Scalding
Writing Hadoop Jobs in Scala using ScaldingToni Cebrián
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
BGOUG15: JSON support in MySQL 5.7
BGOUG15: JSON support in MySQL 5.7BGOUG15: JSON support in MySQL 5.7
BGOUG15: JSON support in MySQL 5.7Georgi Kodinov
 
Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020InfluxData
 
Scoobi - Scala for Startups
Scoobi - Scala for StartupsScoobi - Scala for Startups
Scoobi - Scala for Startupsbmlever
 

Was ist angesagt? (20)

Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
Cutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryCutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQuery
 
Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch?
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Spark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSpark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. Jyotiska
 
DB2 Native XML
DB2 Native XMLDB2 Native XML
DB2 Native XML
 
SQL to Hive Cheat Sheet
SQL to Hive Cheat SheetSQL to Hive Cheat Sheet
SQL to Hive Cheat Sheet
 
Scalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/CascadingScalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/Cascading
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xquery
 
Building data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyBuilding data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemy
 
Writing Hadoop Jobs in Scala using Scalding
Writing Hadoop Jobs in Scala using ScaldingWriting Hadoop Jobs in Scala using Scalding
Writing Hadoop Jobs in Scala using Scalding
 
Php forum2015 tomas_final
Php forum2015 tomas_finalPhp forum2015 tomas_final
Php forum2015 tomas_final
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Sql cheat sheet
Sql cheat sheetSql cheat sheet
Sql cheat sheet
 
LibreCat::Catmandu
LibreCat::CatmanduLibreCat::Catmandu
LibreCat::Catmandu
 
BGOUG15: JSON support in MySQL 5.7
BGOUG15: JSON support in MySQL 5.7BGOUG15: JSON support in MySQL 5.7
BGOUG15: JSON support in MySQL 5.7
 
Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020
 
Scoobi - Scala for Startups
Scoobi - Scala for StartupsScoobi - Scala for Startups
Scoobi - Scala for Startups
 
Scalding for Hadoop
Scalding for HadoopScalding for Hadoop
Scalding for Hadoop
 

Ähnlich wie Kotlin decoration - February Berlin Kotlin Meetup

Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalystsvilen.ivanov
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguajeKotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguajeVíctor Leonel Orozco López
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in SpaceGarth Gilmour
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmersAlexander Varwijk
 
BOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsBOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsPeter Pilgrim
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run themFilipe Ximenes
 
CoffeeScript Design Patterns
CoffeeScript Design PatternsCoffeeScript Design Patterns
CoffeeScript Design PatternsTrevorBurnham
 
The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210Mahmoud Samir Fayed
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with KotlinMurat Yener
 
MapReduce with Scalding @ 24th Hadoop London Meetup
MapReduce with Scalding @ 24th Hadoop London MeetupMapReduce with Scalding @ 24th Hadoop London Meetup
MapReduce with Scalding @ 24th Hadoop London MeetupLandoop Ltd
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsMykyta Protsenko
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryTatsuhiko Miyagawa
 
Terrastore - A document database for developers
Terrastore - A document database for developersTerrastore - A document database for developers
Terrastore - A document database for developersSergio Bossa
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesLindsay Holmwood
 

Ähnlich wie Kotlin decoration - February Berlin Kotlin Meetup (20)

Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguajeKotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
Kotlin+MicroProfile: Enseñando trucos de 20 años a un nuevo lenguaje
 
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
Using Kotlin, to Create Kotlin,to Teach Kotlin,in SpaceUsing Kotlin, to Create Kotlin,to Teach Kotlin,in Space
Using Kotlin, to Create Kotlin, to Teach Kotlin, in Space
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
BOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala appsBOF2644 Developing Java EE 7 Scala apps
BOF2644 Developing Java EE 7 Scala apps
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
CoffeeScript Design Patterns
CoffeeScript Design PatternsCoffeeScript Design Patterns
CoffeeScript Design Patterns
 
Spark training-in-bangalore
Spark training-in-bangaloreSpark training-in-bangalore
Spark training-in-bangalore
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with Kotlin
 
MapReduce with Scalding @ 24th Hadoop London Meetup
MapReduce with Scalding @ 24th Hadoop London MeetupMapReduce with Scalding @ 24th Hadoop London Meetup
MapReduce with Scalding @ 24th Hadoop London Meetup
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and Ops
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
 
SCALA - Functional domain
SCALA -  Functional domainSCALA -  Functional domain
SCALA - Functional domain
 
Terrastore - A document database for developers
Terrastore - A document database for developersTerrastore - A document database for developers
Terrastore - A document database for developers
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
Guillotina
GuillotinaGuillotina
Guillotina
 

Kürzlich hochgeladen

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 

Kürzlich hochgeladen (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

Kotlin decoration - February Berlin Kotlin Meetup

  • 1. Sinan Kozak @snnkzkFebruary 20th, 2020 Kotlin Delegation
  • 2. Page @snnkzk In software engineering, the delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as an inheritance. (https://en.wikipedia.org/wiki/Delegation_pattern) 1
  • 3. Page @snnkzk – Property delegation – Implementation delegation Kotlin Delegation Features 2
  • 4. Page – Manually implemented logic inside get/set methods – Code duplication – Hard to test every usage @snnkzk Without Property Delegation 3
  • 5. Page @snnkzk Logic in get method private var _name: String? = null fun getName(): String { if (_name == null) { _name = ”Sinan" } return _name!! } 4
  • 6. Page @snnkzk Logic in get method private var _name: String? = null fun getName(): String { if (_name == null) { _name = ”Sinan" } return _name!! } val name: String by lazy { "Sinan" } 5
  • 7. Page @snnkzk – Need nullable private backing field – Code duplication for every new field – Backing field is useable in same class @snnkzk Logic in get method for object creation private var _name: String? = null fun getName(): String { if (_name == null) { _name = ”Sinan" } return _name!! } 6
  • 8. Page @snnkzk – A helper from Kotlin standard library – An interface with a value object – Run function when property is used – “lazy() is a function that takes a lambda and returns an instance of Lazy<T> which can serve as a delegate for implementing a lazy property: the first call to get() executes the lambda passed to lazy() and remembers the result, subsequent calls to get() simply return the remembered result.” What is lazy? 7
  • 9. Page – Language word for delegation – For delegation property, there are two interfaces • ReadWriteProperty • ReadOnlyProperty – For implementation delegation it expectes `interface by instance` @snnkzk What is ‘by’? 8
  • 10. Page – Really similar to lazy – Creates a new view model and caches it – Custom view model factory can be passed @snnkzk by viewModels() from AndroidX 9
  • 11. Page – Really similar to lazy – Creates a new view model and caches it – Custom view model factory can be passed @snnkzk by viewModels() from AndroidX 10 val model: MyViewModel by viewModels()
  • 12. Page – It is possible to create delegation depending on other types – Instance will be passed as ref – @AskAshDavies will write about it, maybe even a library @snnkzk Custom Examples private var SharedPreferences.somePref: String by sharedPreferencesStringOrDefault(”default value") 11
  • 14. Page – Delegate interface to different instance – Prevent Code duplication – Helps to contain logic as unit – Compiler rewrite our classes with delegation @snnkzk Implementation Delegation 13
  • 15. Page – import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class JavaDelegatedList<T> implements List<T> { private final List<T> innerList; private int addCount = 0; public JavaDelegatedList(List<T> innerList) { this.innerList = innerList; } @Override public int size() { return innerList.size(); } @Override public boolean isEmpty() { return innerList.isEmpty(); } @Override public boolean contains(Object o) { return innerList.contains(o); } @Override public Iterator<T> iterator() { return innerList.iterator(); } @snnkzk Java Delegation @Override public Object[] toArray() { return innerList.toArray(); } @Override public boolean add(T o) { addCount++; return innerList.add(o); } @Override public boolean remove(Object o) { return innerList.remove(o); } @Override public boolean addAll(Collection c) { addCount += c.size(); return innerList.addAll(c); } @Override public boolean addAll(int index, Collection c) { addCount += c.size(); return innerList.addAll(index, c); } @Override public void clear() { innerList.clear(); } @Override public T get(int index) { return innerList.get(index); } @Override public T set(int index, T element) { return innerList.set(index, element); } @Override public void add(int index, T element) { addCount++; innerList.add(index, element); } @Override public T remove(int index) { return innerList.remove(index); } @Override public int indexOf(Object o) { return innerList.indexOf(o); } @Override public int lastIndexOf(Object o) { return innerList.lastIndexOf(o); } @Override public ListIterator<T> listIterator() { return innerList.listIterator(); } @Override public ListIterator<T> listIterator(int index) { return innerList.listIterator(index); } @Override public List<T> subList(int fromIndex, int toIndex) { return innerList.subList(fromIndex, toIndex); } @Override public boolean retainAll(Collection c) { return false; } @Override public boolean removeAll(Collection c) { return false; } @Override public boolean containsAll(Collection c) { return false; } @Override public <T> T[] toArray(T[] a) { return innerList.toArray(a); } } 14
  • 16. Page @snnkzk Implementation Delegation class KotlinDelegateList(private val innerList: List<String>) : List<String> by innerList 15
  • 17. Page – That is what they thought us 🤔 – We also learned why. Thanks Android – Activities and Fragments forces us to use inheritance @snnkzk Favour composition over inheritance 16
  • 18. Page – That is what they thought us 🤔 – We also learned why. Thanks Android – Activities and Fragments forces us to use inheritance – Jean-Michel Fayard https://dev.to/jmfayard/android-s-billion-dollar-mistake-327b @snnkzk Favour composition over inheritance 17
  • 19. Page @snnkzk – Classes are final by default Why is Kotlin different 18
  • 20. Page @snnkzk – Classes are final by default – Data classes cannot be open – You can inherit a data class from a non-data class. Inheriting a data class from another data class is not allowed because there is no way to make compiler- generated data class methods work consistently and intuitively in case of inheritance. (Answer from JetBrain team) Why is Kotlin different 19
  • 21. Page @snnkzk interface ClosedShape { fun area(): Int } class Rectangle(val width: Int, val height: Int) : ClosedShape { override fun area() = width * height } class Circle(val radius: Int): ClosedShape { override fun area(): Int = (Math.PI * radius * radius).toInt() } // We can have circle or rectangle window class Window(private val bounds: ClosedShape) : ClosedShape by bounds 20
  • 22. Page – Need water, milk and espresso – All have volume, name and price – Any product needs to have invoice @snnkzk Coffee Shop Program Example 21
  • 23. Page @snnkzk Coffee Shop Program Example data class Water( override val name: String, override val volume: Double, override val cost: Double = volume * 0.0 ) : Beverage 22
  • 24. Page @snnkzk Coffee Shop Program Example data class Water( override val name: String, override val volume: Double, override val cost: Double = volume * 0.0 ) : Beverage data class HotWater(override val volume: Double) : Beverage by Water(name = "Hot water", volume = volume) data class ColdWater(override val volume: Double) : Beverage by Water(name = "Cold water", volume = volume) 23
  • 25. Page @snnkzk Coffee Shop Program Example data class Milk( override val name: String, override val volume: Double, override val cost: Double = volume * 1 ) : Beverage 24
  • 26. Page @snnkzk Coffee Shop Program Example data class Milk( override val name: String, override val volume: Double, override val cost: Double = volume * 1 ) : Beverage data class HotMilk(override val volume: Double) : Beverage by Milk(name = "Hot milk", volume = volume) data class ColdMilk(override val volume: Double) : Beverage by Milk(name = "Cold milk", volume = volume) 25
  • 27. Page @snnkzk Coffee Shop Program Example data class Espresso( override val volume: Double = 1.0, private val base: Beverage = HotWater(volume) ) : Beverage by base { override val name: String = "Espresso" override val cost: Double = base.cost + volume * 3 } 26
  • 28. Page – We have base beverages water, milk and espresso – We can create an extension function for plus operation – End result of plus will be final product – data class CombinedBeverage @snnkzk Coffee Shop Program Example 27
  • 29. Page @snnkzk Coffee Shop Program Example data class Coffee(override val name: String = "Coffee") : Beverage by Espresso() + HotWater(volume = 2.0) data class ColdCoffee(override val name: String = "Cold coffee") : Beverage by Espresso() + ColdWater(volume = 2.0) data class HotMilkCoffee(override val name: String = "Hot Milk Coffee") : Beverage by Espresso() + HotMilk(volume = 2.0) data class ColdMilkCoffee(override val name: String = "Cold Milk Coffee") : Beverage by Espresso() + ColdMilk(volume = 2.0) data class DoubleMilkCoffee(override val name: String = "DoubleMilkCoffee") : Beverage by Espresso() + HotMilk(volume = 4.0) 28
  • 30. Page @snnkzk – println("Espresso = ${Espresso().invoice()}") // Espresso = 1.0 cc Hot water costs 0.0 – println("Coffee = ${Coffee().invoice()}") // Coffee = 3.0 cc Espresso + Hot water costs 3.0 – println("ColdCoffee = ${ColdCoffee().invoice()}") // ColdCoffee = 3.0 cc Espresso + Cold water costs 3.0 – println("HotMilkCoffee = ${HotMilkCoffee().invoice()}") // HotMilkCoffee = 3.0 cc Espresso + Hot milk costs 5.0 – println("ColdMilkCoffee = ${ColdMilkCoffee().invoice()}") // ColdMilkCoffee = 3.0 cc Espresso + Cold milk costs 5.0 – println("DoubleMilkCoffee = ${DoubleMilkCoffee().invoice()}") // DoubleMilkCoffee = 5.0 cc Espresso + Hot milk costs 7.0 Invoice calls Coffee Shop Program Example 29
  • 31. Page – Be careful with ‘this’ usage – return this – ‘this’ always aims the class it is in @snnkzk Scoped ‘this’ 30
  • 32. Page @snnkzk Scoped ‘this’ interface Beverage { val volume: Double val cost: Double val name: String fun invoice(): String = "$volume cc $name costs $cost" fun returnThis(): Beverage } 31
  • 33. Page @snnkzk Scoped ‘this’ data class Water( override val name: String, override val volume: Double, override val cost: Double = volume * 0.0 ) : Beverage { override fun returnThis(): Beverage = this } data class Milk( override val name: String, override val volume: Double, override val cost: Double = volume * 1 ) : Beverage { override fun returnThis(): Beverage = this } data class Espresso( override val volume: Double = 1.0, private val base: Beverage = HotWater(volume) ) : Beverage by base { override val name: String = "Espresso" override val cost: Double = base.cost + volume * 3 } 32
  • 34. Page @snnkzk Scoped ‘this’ println(”Espresso = ${Espresso().returnThis()}") 33
  • 35. Page @snnkzk Espresso = Water(name=Hot water, volume=1.0, cost=0.0) Scoped ‘this’ println(”Espresso = ${Espresso().returnThis()}") data class Espresso( override val volume: Double = 1.0, private val base: Beverage ) : Beverage by base { override val name: String = "Espresso override val cost: Double = … } 34
  • 36. Page – Extension on interface works for every class – Extension override is possible – Casting is required for using overridden extension @snnkzk Extension function parent class vs child class 35
  • 37. Page Thank you for your attention. Questions? Sinan Kozak @snnkzk @snnkzk36

Hinweis der Redaktion

  1. So everyone knows composition/ decorator pattern I didn’t understand at what kotlin delegation gives us
  2. Inheritance creates base classes Not possible multi class inheritance inherited classe can affect each other
  3. Milsoft Swing View creating on runtime It didn’t prevent bugs
  4. ALL we want single line We had over 1.4 million LoC in previous company I cannot imagine how much will it reduce with this anda data classes Depending on total loc / project time. They calculated a java dev writes 4 LoC per hour. I really would like to know what will it be with kotlin
  5. Helper for lazy object creation Gets a block It has thread safety by default but we can lossen it by passing policy Actually interface with some tricks nothing more
  6. Expect operator function
  7. If you are using Vm Activities and fragments needs to create/get VM Besides different class information code will be identical
  8. If you are using Vm Activities and fragments needs to create/get VM Besides different class information code will be identical
  9. For not repeating getString setString methods No need to repeat editor method Setting and Getting will use our method ASH It is fully tested because it is actually simple 10 lines of class END
  10. WATER
  11. Compiler magic Compiler adds every interface method to our class Next java
  12. It is easy to choose inheritance over this uglyness Delegation for java developer is hard if interface gets big Every change to interface and base class force us to change this implementation Tests for base class needs to be written for new class too
  13. This is what we want
  14. Java doesn’t allow multiple inheritance Multi Inheritance is pain Android uses inheritance all over the place
  15. Billion dollar mistake Jean Michel
  16. Wikipedia example While creating window we don’t care We can have different window type on runtime
  17. My example project. I used similar example from Head First Design Patters book Data classes Everything needs to be data classes So interface for data class
  18. Next MILK
  19. Next ESPRESSO
  20. Final product we can sell in coffee shop All of them beverages
  21. Everyone of them unique It is not decorator pattern but example for delegation
  22. Write test as much as possible Don’t return this If you return this or use this, override those method in new class
  23. Updaate interface
  24. Updated classes Espresso didn’t changed because base should alreadty implement new method
  25. Creating a new espresso should return espreso While reading code we in team expected it will always return espresso. Because that is this right :smile
  26. Returns base class
  27. Extension function Give string example
  28. Q/A?