SlideShare uma empresa Scribd logo
1 de 59
Baixar para ler offline
ADVANCED
KOTLIN TRICKS
Ubiratan Soares
September / 2018
STDLIB :
THE FORGOTTEN
FUNCTIONS
Repeat
fun severalPrints() =
repeat(times = 10) {
print("Hey!")
}
fun validate(name: String) =
name.length in 2!"20
fun saveUser(name: String) =
validate(name)
.also { saveWith(name) }
Also
TakeIf
/#$
* Returns `this` value if it satisïŹes the
* given [predicate] or `null`, if it doesn't.
%&
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeIf(predicate: (T) '( Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (predicate(this)) this else null
}
TakeIf
/#$
* Returns `this` value if it satisïŹes the
* given [predicate] or `null`, if it doesn't.
%&
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeIf(predicate: (T) '( Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (predicate(this)) this else null
}
TakeUnless
/#$
* Returns `this` value if it _does not_ satisfy
* the given [predicate] or `null`, if it does.
%&
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeUnless(predicate: (T) '( Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (!predicate(this)) this else null
}
fun names() =
if (Random().nextBoolean()) "Elvis"
else "Presley"
val shortName =
names()
.takeIf { it.length )* 5 }
+, "Too long"
val longName =
names()
.takeUnless { it.length )* 5 }
+, "Too Short"
INVOKING
LIKE A PRO
class DeepLinkParser {
fun parse(uri : String) : ProductId {
// Parse your URI and extract product id
}
}
class DeepLinkHandler(
val parser: DeepLinkParser) {
operator fun invoke(url : String) : Intent {
// Handle with parser and get your Intent
}
}
class DeepLinkHandler(
val parser: DeepLinkParser) {
operator fun invoke(url : String) : Intent {
// Handle with parser and get your Intent
}
}
Invoking Instances
val parser = DeepLinkParser()
val handler = DeepLinkHandler(parser)
val intent = handler("myapp:-.product/123456")
// Launch your Activity 🚀
A tiny web DSL
sealed class HTTPMethod
object GET : HTTPMethod()
object POST : HTTPMethod()
class Status {
var code: Int = 0
var payload: String = ""
}
class HttpRequest {
var method: HTTPMethod = GET
var body: String = ""
var query: String = ""
}
class HttpResponse {
var internalMessage: String = ""
lateinit var status: Status
}
class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun handle() {
-. TODO
}
}
fun endpoint(
path: String,
block: Endpoint.() '( Unit) =
Endpoint().apply { block() }.handle()
endpoint("/api/product") {
}
class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun request(block: HttpRequest.() '( Unit) {
request = HttpRequest().apply { block() }
}
fun response(block: HttpResponse.() '( Unit) {
response = HttpResponse().apply { block() }
}
fun handle() {
-. TODO
}
}
endpoint("/api/product") {
request {
method = POST,
body = "{ Some json }"
}
response {
}
}
endpoint("/api/product") {
request {
method = POST,
body = "{ Some json }"
}
response {
status {
code = 200
payload = "{ Some json }"
}
}
}
class HttpResponse {
var internalMessage: String = ""
lateinit var status: Status
fun status(setup: Status.() '( Unit) {
status = Status().apply { setup() }
}
}
endpoint("/api/product") {
request {
method = POST,
body = "{ Some json }"
}
response {
status {
code = 200
payload = "{ Some json }"
}
}
}
Can we do better ?
đŸ€”
class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun request(block: HttpRequest.() '( Unit) {
request = HttpRequest().apply { block() }
}
fun response(block: HttpResponse.() '( Unit) {
response = HttpResponse().apply { block() }
}
fun handle() {
-. TODO
}
}
class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun request(block: HttpRequest.() '( Unit) {
request = HttpRequest().apply { block() }
}
fun response(block: HttpResponse.() '( Unit) {
response = HttpResponse().apply { block() }
}
fun handle() {
-. TODO
}
}
👀
class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun request(block: HttpRequest.() '( Unit) {
request = HttpRequest().apply { block() }
}
fun response(block: HttpResponse.() '( Unit) {
response = HttpResponse().apply { block() }
}
fun handle() {
-. TODO
}
}
class HttpResponse {
var internalMessage: String = ""
lateinit var status: Status
fun status(setup: Status.() '( Unit) {
status = Status().apply { setup() }
}
}
class Endpoint {
lateinit var request: HttpRequest
lateinit var response: HttpResponse
fun request(block: HttpRequest.() '( Unit) {
request = HttpRequest().apply { block() }
}
fun handle() {
-. TODO
}
}
class HttpResponse {
var internalMessage: String = ""
lateinit var status: Status
operator fun invoke(
setup: Status.() -> Unit) {
status = Status().apply { setup() }
}
}
endpoint("/api/product") {
request {
method = POST
body = "{ Some json }"
}
response {
code = 200
payload = "{ Some json }"
}
}
endpoint("/api/product") {
request {
method = POST,
body = "{ Some json }"
}
response {
status {
code = 200
payload = "{ Some json }"
}
}
}
Before After
http://shop.oreilly.com/product/0636920052999.do
AWESOME
COMPANIONS
interface FormValidator {
fun validate(name: String?): Boolean
}
class FormPresenter {
private companion object : FormValidator {
override fun validate(name: String?) =
name/0isNotEmpty()
+, throw IllegalArgumentException("Invalid Name")
}
}
interface FormValidator {
fun validate(name: String?): Boolean
}
class FormPresenter {
private companion object : FormValidator {
override fun validate(name: String?) =
name/0isNotEmpty()
+, throw IllegalArgumentException("Invalid Name")
}
}
Fake Constructors
val sampa = Location("23.5505° S", "46.6333° W")
data class Location(
val latitude: Float,
val longitude: Float
)
đŸ€”
data class Location(
val latitude: Float,
val longitude: Float) {
companion object {
operator fun invoke(lat: String, long: String) =
Location(parse(lat), parse(long))
private fun parse(coordinate: String): Float {
-. convert the String representation
}
}
}
data class Location(
val latitude: Float,
val longitude: Float) {
companion object {
operator fun invoke(lat: String, long: String) =
Location(parse(lat), parse(long))
private fun parse(coordinate: String): Float {
-. convert the String representation
}
}
}
NOTHING
ELSE
MATTERS
The Nothing Type
https://en.wikipedia.org/wiki/Bottom_type
" In type theory, a theory within mathematical logic,
the bottom type is the type that has no values. It is also
called the zero or empty type, and is sometimes denoted
with falsum (⊄).
A function whose return type is bottom cannot return any
value. In the Curry–Howard correspondence, the bottom
type corresponds to falsity. "
/#$
* The type with only one value: the Unit object.
* This type corresponds to the `void` type
* in Java.
%&
public object Unit {
override fun toString() = "kotlin.Unit"
}
Kotlin Types
Nothing
SomeType
Any
Nothing?
SomeType?
Any?
/#$
* Always throws [NotImplementedError]
* stating that operation is not implemented.
%&
@kotlin.internal.InlineOnly
public inline fun TODO(): Nothing =
throw NotImplementedError()
Nothing and ïŹ‚ow control
inline fun <T> guard(
receiver: T?,
block: () '( Nothing): T {
if (receiver 12 null) { block() }
return receiver
}
https://gist.github.com/hzsweers/463500043b1a9708ba4e26c7ad1862fd
fun guarding() {
val conference: String? = "Kotlin Summit"
val guarded = guard(conference) { return }
val guardedAgain = guard(conference) {
throw IllegalStateException("Null konf")
}
val invalid = guard(conference) {
-.Compiler error because not
-.returned or thrown an exception!
}
}
Nothing and Generics
sealed class Tree<out T>
class Node<T>(
val left: Tree<T>,
val right: Tree<T>) : Tree<T>()
class Leaf<T>(val value: T) : Tree<T>()
object Empty : Tree<Nothing>()
val tree = Node(
Leaf("1"),
Node(
Leaf("2"),
Empty
)
)
1
2
sealed class Result<out V, out E>
data class Value<out V>(val value: V) :
Result<V, Nothing>()
data class Error<out E>(val error: E) :
Result<Nothing, E>()
ADVANCING ON
DELEGATION
interface Validation {
fun validate(input: String): Boolean
}
class NameValidator : Validation {
override fun validate(input: String) =
input.isNotEmpty() 34 input.length 56 2
}
Class delegation
val accepted = FormViewModel().validate("Bira")
class FormViewModel : Validation by NameValidator()
Class delegation
class FormViewModel : FormValidator by Internal {
companion object Internal : FormValidator {
override fun validate(name: String?) =
name/0isNotEmpty()+, false
}
}
val rejected = FormViewModel().validate("Hi")
class CheckProïŹle {
companion object : (Int) '( Boolean by ShouldBeLegal
}
val canDrink = CheckProïŹle(35)
object ShouldBeLegal : (Int) '( Boolean {
override fun invoke(age: Int) = age 5618
}
interface HandleSuccess {
fun showResult()
}
interface HandleError {
fun showError()
}
interface LoginScreen : HandleSuccess, HandleError
interface ProductScreen : HandleSuccess, HandleError
Selective delegation
fun <C> performOperation(behavior: C)
where C : HandleSuccess, C : HandleError {
try {
executeSomething()
behavior.showResult()
} catch (error: Throwable) {
behavior.showError()
}
}
Selective delegation
fun <C> performOperation(behavior: C)
where C : HandleSuccess, C : HandleError {
try {
executeSomething()
behavior.showResult()
} catch (error: Throwable) {
behavior.showError()
}
}
PLUS,
ULTRA !!!
What if I told you
that extensions are
not only for objects
???
val checkLegalAge: (Int) '( Boolean = { it 56 18 }
val checkNotDead: (Int) '( Boolean = { it < 150 }
fun ((Int) '( Boolean).report(age: Int) =
this.invoke(age)
.also { print((if (it) "Ok" else "Not OK")) }
fun misjudge(age: Int) =
if (age > 15) checkLegalAge.report(age)
else checkNotDead.invoke(age)
Final Remarks
Kotlin has it's secrets, go explore !!!
Learn more hidden features for fun and proïŹt
https://speakerdeck.com/ubiratansoares
UBIRATAN
SOARES
Computer Scientist by ICMC/USP
Software Engineer, curious guy
Google Developer Expert for Android / Kotlin
Teacher, speaker, etc, etc
THANK YOU
@ubiratanfsoares
ubiratansoares.github.io
https://br.linkedin.com/in/ubiratanfsoares

Mais conteĂșdo relacionado

Mais procurados

Hidden rocks in Oracle ADF
Hidden rocks in Oracle ADFHidden rocks in Oracle ADF
Hidden rocks in Oracle ADF
Euegene Fedorenko
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Anton Arhipov
 
Deep dive into Oracle ADF
Deep dive into Oracle ADFDeep dive into Oracle ADF
Deep dive into Oracle ADF
Euegene Fedorenko
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011
Anton Arhipov
 

Mais procurados (20)

Hidden rocks in Oracle ADF
Hidden rocks in Oracle ADFHidden rocks in Oracle ADF
Hidden rocks in Oracle ADF
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
 
Deep dive into Oracle ADF
Deep dive into Oracle ADFDeep dive into Oracle ADF
Deep dive into Oracle ADF
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011Java Bytecode for Discriminating Developers - JavaZone 2011
Java Bytecode for Discriminating Developers - JavaZone 2011
 
My java file
My java fileMy java file
My java file
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
From typing the test to testing the type
From typing the test to testing the typeFrom typing the test to testing the type
From typing the test to testing the type
 
Google guava
Google guavaGoogle guava
Google guava
 
0003 es5 í•”ì‹Ź ì •ëŠŹ
0003 es5 í•”ì‹Ź ì •ëŠŹ0003 es5 í•”ì‹Ź ì •ëŠŹ
0003 es5 í•”ì‹Ź ì •ëŠŹ
 
Tests unitaires mock_kesako_20130516
Tests unitaires mock_kesako_20130516Tests unitaires mock_kesako_20130516
Tests unitaires mock_kesako_20130516
 
Unbreakable: The Craft of Code
Unbreakable: The Craft of CodeUnbreakable: The Craft of Code
Unbreakable: The Craft of Code
 
Con5623 pdf 5623_001
Con5623 pdf 5623_001Con5623 pdf 5623_001
Con5623 pdf 5623_001
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Pure kotlin
Pure kotlinPure kotlin
Pure kotlin
 
ES3-2020-07 Testing techniques
ES3-2020-07 Testing techniquesES3-2020-07 Testing techniques
ES3-2020-07 Testing techniques
 
To be Continued - multithreading with Project Loom and Kotlin's Coroutines
To be Continued - multithreading with Project Loom and Kotlin's CoroutinesTo be Continued - multithreading with Project Loom and Kotlin's Coroutines
To be Continued - multithreading with Project Loom and Kotlin's Coroutines
 
LISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesLISA QooxdooTutorial Slides
LISA QooxdooTutorial Slides
 

Semelhante a Kotlin : Advanced Tricks - Ubiratan Soares

Lego: A brick system build by scala
Lego: A brick system build by scalaLego: A brick system build by scala
Lego: A brick system build by scala
lunfu zhong
 

Semelhante a Kotlin : Advanced Tricks - Ubiratan Soares (20)

ă€ăăŁăŠă‚ăăŒ Kotlin DSL ~æ‹ĄćŒ”ç·š~
ă€ăăŁăŠă‚ăăŒ Kotlin DSL ~æ‹ĄćŒ”ç·š~ă€ăăŁăŠă‚ăăŒ Kotlin DSL ~æ‹ĄćŒ”ç·š~
ă€ăăŁăŠă‚ăăŒ Kotlin DSL ~æ‹ĄćŒ”ç·š~
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
2014-11-01 01 Đ”Đ”ĐœĐžŃ ĐĐ”Đ»ŃŽĐ±ĐžĐœ. О ŃĐŸŃ€Ń‚Đ°Ń… ĐșĐŸŃ„Đ”
2014-11-01 01 Đ”Đ”ĐœĐžŃ ĐĐ”Đ»ŃŽĐ±ĐžĐœ. О ŃĐŸŃ€Ń‚Đ°Ń… ĐșĐŸŃ„Đ”2014-11-01 01 Đ”Đ”ĐœĐžŃ ĐĐ”Đ»ŃŽĐ±ĐžĐœ. О ŃĐŸŃ€Ń‚Đ°Ń… ĐșĐŸŃ„Đ”
2014-11-01 01 Đ”Đ”ĐœĐžŃ ĐĐ”Đ»ŃŽĐ±ĐžĐœ. О ŃĐŸŃ€Ń‚Đ°Ń… ĐșĐŸŃ„Đ”
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
Miracle of std lib
Miracle of std libMiracle of std lib
Miracle of std lib
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using Scala
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Dip into Coroutines - KTUG Munich 202303
Dip into Coroutines - KTUG Munich 202303Dip into Coroutines - KTUG Munich 202303
Dip into Coroutines - KTUG Munich 202303
 
SDC - EinfĂŒhrung in Scala
SDC - EinfĂŒhrung in ScalaSDC - EinfĂŒhrung in Scala
SDC - EinfĂŒhrung in Scala
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Kotlin
KotlinKotlin
Kotlin
 
JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?JDD 2016 - Pawel Byszewski - Kotlin, why?
JDD 2016 - Pawel Byszewski - Kotlin, why?
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Lego: A brick system build by scala
Lego: A brick system build by scalaLego: A brick system build by scala
Lego: A brick system build by scala
 

Mais de iMasters

Mais de iMasters (20)

O que vocĂȘ precisa saber para modelar bancos de dados NoSQL - Dani Monteiro
O que vocĂȘ precisa saber para modelar bancos de dados NoSQL - Dani MonteiroO que vocĂȘ precisa saber para modelar bancos de dados NoSQL - Dani Monteiro
O que vocĂȘ precisa saber para modelar bancos de dados NoSQL - Dani Monteiro
 
Postgres: wanted, beloved or dreaded? - Fabio Telles
Postgres: wanted, beloved or dreaded? - Fabio TellesPostgres: wanted, beloved or dreaded? - Fabio Telles
Postgres: wanted, beloved or dreaded? - Fabio Telles
 
Por que minha query esta lenta? - Suellen Moraes
Por que minha query esta lenta? - Suellen MoraesPor que minha query esta lenta? - Suellen Moraes
Por que minha query esta lenta? - Suellen Moraes
 
Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig...
Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig...Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig...
Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig...
 
ORMs heróis ou vilÔes dentro da arquitetura de dados? - Otåvio gonçalves
ORMs heróis ou vilÔes dentro da arquitetura de dados? - Otåvio gonçalvesORMs heróis ou vilÔes dentro da arquitetura de dados? - Otåvio gonçalves
ORMs heróis ou vilÔes dentro da arquitetura de dados? - Otåvio gonçalves
 
SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -...
SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -...SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -...
SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -...
 
Arquitetando seus dados na prĂĄtica para a LGPD - Alessandra Martins
Arquitetando seus dados na prĂĄtica para a LGPD - Alessandra MartinsArquitetando seus dados na prĂĄtica para a LGPD - Alessandra Martins
Arquitetando seus dados na prĂĄtica para a LGPD - Alessandra Martins
 
O papel do DBA no mundo de ciĂȘncia de dados e machine learning - Mauro Pichil...
O papel do DBA no mundo de ciĂȘncia de dados e machine learning - Mauro Pichil...O papel do DBA no mundo de ciĂȘncia de dados e machine learning - Mauro Pichil...
O papel do DBA no mundo de ciĂȘncia de dados e machine learning - Mauro Pichil...
 
Desenvolvimento Mobile HĂ­brido, Nativo ou Web: Quando usĂĄ-los - Juliana Chahoud
Desenvolvimento Mobile HĂ­brido, Nativo ou Web: Quando usĂĄ-los - Juliana ChahoudDesenvolvimento Mobile HĂ­brido, Nativo ou Web: Quando usĂĄ-los - Juliana Chahoud
Desenvolvimento Mobile HĂ­brido, Nativo ou Web: Quando usĂĄ-los - Juliana Chahoud
 
Use MDD e faça as mĂĄquinas trabalharem para vocĂȘ - Andreza Leite
 Use MDD e faça as mĂĄquinas trabalharem para vocĂȘ - Andreza Leite Use MDD e faça as mĂĄquinas trabalharem para vocĂȘ - Andreza Leite
Use MDD e faça as mĂĄquinas trabalharem para vocĂȘ - Andreza Leite
 
Entendendo os porquĂȘs do seu servidor - Talita Bernardes
Entendendo os porquĂȘs do seu servidor - Talita BernardesEntendendo os porquĂȘs do seu servidor - Talita Bernardes
Entendendo os porquĂȘs do seu servidor - Talita Bernardes
 
Backend performåtico além do "coloca mais måquina lå" - Diana Arnos
Backend performåtico além do "coloca mais måquina lå" - Diana ArnosBackend performåtico além do "coloca mais måquina lå" - Diana Arnos
Backend performåtico além do "coloca mais måquina lå" - Diana Arnos
 
Dicas para uma maior performance em APIs REST - Renato Groffe
Dicas para uma maior performance em APIs REST - Renato GroffeDicas para uma maior performance em APIs REST - Renato Groffe
Dicas para uma maior performance em APIs REST - Renato Groffe
 
7 dicas de desempenho que equivalem por 21 - Danielle Monteiro
7 dicas de desempenho que equivalem por 21 - Danielle Monteiro7 dicas de desempenho que equivalem por 21 - Danielle Monteiro
7 dicas de desempenho que equivalem por 21 - Danielle Monteiro
 
Quem se importa com acessibilidade Web? - Mauricio Maujor
Quem se importa com acessibilidade Web? - Mauricio MaujorQuem se importa com acessibilidade Web? - Mauricio Maujor
Quem se importa com acessibilidade Web? - Mauricio Maujor
 
Service Mesh com Istio e Kubernetes - Wellington Figueira da Silva
Service Mesh com Istio e Kubernetes - Wellington Figueira da SilvaService Mesh com Istio e Kubernetes - Wellington Figueira da Silva
Service Mesh com Istio e Kubernetes - Wellington Figueira da Silva
 
Erros: Como eles vivem, se alimentam e se reproduzem? - Augusto Pascutti
Erros: Como eles vivem, se alimentam e se reproduzem? - Augusto PascuttiErros: Como eles vivem, se alimentam e se reproduzem? - Augusto Pascutti
Erros: Como eles vivem, se alimentam e se reproduzem? - Augusto Pascutti
 
Elasticidade e engenharia de banco de dados para alta performance - Rubens G...
Elasticidade e engenharia de banco de dados para alta performance  - Rubens G...Elasticidade e engenharia de banco de dados para alta performance  - Rubens G...
Elasticidade e engenharia de banco de dados para alta performance - Rubens G...
 
Construindo aplicaçÔes mais confiantes - Carolina Karklis
Construindo aplicaçÔes mais confiantes - Carolina KarklisConstruindo aplicaçÔes mais confiantes - Carolina Karklis
Construindo aplicaçÔes mais confiantes - Carolina Karklis
 
Monitoramento de AplicaçÔes - Felipe Regalgo
Monitoramento de AplicaçÔes - Felipe RegalgoMonitoramento de AplicaçÔes - Felipe Regalgo
Monitoramento de AplicaçÔes - Felipe Regalgo
 

Último

Lucknow ❀CALL GIRL 88759*99948 ❀CALL GIRLS IN Lucknow ESCORT SERVICE❀CALL GIRL
Lucknow ❀CALL GIRL 88759*99948 ❀CALL GIRLS IN Lucknow ESCORT SERVICE❀CALL GIRLLucknow ❀CALL GIRL 88759*99948 ❀CALL GIRLS IN Lucknow ESCORT SERVICE❀CALL GIRL
Lucknow ❀CALL GIRL 88759*99948 ❀CALL GIRLS IN Lucknow ESCORT SERVICE❀CALL GIRL
imonikaupta
 
đŸ“±Dehradun Call Girls Service đŸ“±â˜Žïž +91'905,3900,678 â˜ŽïžđŸ“± Call Girls In Dehradun đŸ“±
đŸ“±Dehradun Call Girls Service đŸ“±â˜Žïž +91'905,3900,678 â˜ŽïžđŸ“± Call Girls In Dehradun đŸ“±đŸ“±Dehradun Call Girls Service đŸ“±â˜Žïž +91'905,3900,678 â˜ŽïžđŸ“± Call Girls In Dehradun đŸ“±
đŸ“±Dehradun Call Girls Service đŸ“±â˜Žïž +91'905,3900,678 â˜ŽïžđŸ“± Call Girls In Dehradun đŸ“±
@Chandigarh #call #Girls 9053900678 @Call #Girls in @Punjab 9053900678
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
SUHANI PANDEY
 
Wadgaon Sheri $ Call Girls Pune 10k @ I'm VIP Independent Escorts Girls 80057...
Wadgaon Sheri $ Call Girls Pune 10k @ I'm VIP Independent Escorts Girls 80057...Wadgaon Sheri $ Call Girls Pune 10k @ I'm VIP Independent Escorts Girls 80057...
Wadgaon Sheri $ Call Girls Pune 10k @ I'm VIP Independent Escorts Girls 80057...
SUHANI PANDEY
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
SUHANI PANDEY
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
JOHNBEBONYAP1
 
valsad Escorts Service ☎ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 

Último (20)

Hire↠Young Call Girls in Tilak nagar (Delhi) ☎ 9205541914 ☎ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎ 9205541914 ☎ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎ 9205541914 ☎ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎ 9205541914 ☎ Independent Esc...
 
Lucknow ❀CALL GIRL 88759*99948 ❀CALL GIRLS IN Lucknow ESCORT SERVICE❀CALL GIRL
Lucknow ❀CALL GIRL 88759*99948 ❀CALL GIRLS IN Lucknow ESCORT SERVICE❀CALL GIRLLucknow ❀CALL GIRL 88759*99948 ❀CALL GIRLS IN Lucknow ESCORT SERVICE❀CALL GIRL
Lucknow ❀CALL GIRL 88759*99948 ❀CALL GIRLS IN Lucknow ESCORT SERVICE❀CALL GIRL
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
đŸ“±Dehradun Call Girls Service đŸ“±â˜Žïž +91'905,3900,678 â˜ŽïžđŸ“± Call Girls In Dehradun đŸ“±
đŸ“±Dehradun Call Girls Service đŸ“±â˜Žïž +91'905,3900,678 â˜ŽïžđŸ“± Call Girls In Dehradun đŸ“±đŸ“±Dehradun Call Girls Service đŸ“±â˜Žïž +91'905,3900,678 â˜ŽïžđŸ“± Call Girls In Dehradun đŸ“±
đŸ“±Dehradun Call Girls Service đŸ“±â˜Žïž +91'905,3900,678 â˜ŽïžđŸ“± Call Girls In Dehradun đŸ“±
 
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >àŒ’8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >àŒ’8448380779 Escort ServiceBusty Desi⚡Call Girls in Vasundhara Ghaziabad >àŒ’8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >àŒ’8448380779 Escort Service
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
đ“€€Call On 7877925207 đ“€€ Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
đ“€€Call On 7877925207 đ“€€ Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...đ“€€Call On 7877925207 đ“€€ Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
đ“€€Call On 7877925207 đ“€€ Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls DubaiDubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
 
Microsoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck MicrosoftMicrosoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck Microsoft
 
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
 
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
 
Wadgaon Sheri $ Call Girls Pune 10k @ I'm VIP Independent Escorts Girls 80057...
Wadgaon Sheri $ Call Girls Pune 10k @ I'm VIP Independent Escorts Girls 80057...Wadgaon Sheri $ Call Girls Pune 10k @ I'm VIP Independent Escorts Girls 80057...
Wadgaon Sheri $ Call Girls Pune 10k @ I'm VIP Independent Escorts Girls 80057...
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
 
valsad Escorts Service ☎ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
 

Kotlin : Advanced Tricks - Ubiratan Soares

  • 4. fun validate(name: String) = name.length in 2!"20 fun saveUser(name: String) = validate(name) .also { saveWith(name) } Also
  • 5. TakeIf /#$ * Returns `this` value if it satisïŹes the * given [predicate] or `null`, if it doesn't. %& @kotlin.internal.InlineOnly @SinceKotlin("1.1") public inline fun <T> T.takeIf(predicate: (T) '( Boolean): T? { contract { callsInPlace(predicate, InvocationKind.EXACTLY_ONCE) } return if (predicate(this)) this else null }
  • 6. TakeIf /#$ * Returns `this` value if it satisïŹes the * given [predicate] or `null`, if it doesn't. %& @kotlin.internal.InlineOnly @SinceKotlin("1.1") public inline fun <T> T.takeIf(predicate: (T) '( Boolean): T? { contract { callsInPlace(predicate, InvocationKind.EXACTLY_ONCE) } return if (predicate(this)) this else null }
  • 7. TakeUnless /#$ * Returns `this` value if it _does not_ satisfy * the given [predicate] or `null`, if it does. %& @kotlin.internal.InlineOnly @SinceKotlin("1.1") public inline fun <T> T.takeUnless(predicate: (T) '( Boolean): T? { contract { callsInPlace(predicate, InvocationKind.EXACTLY_ONCE) } return if (!predicate(this)) this else null }
  • 8. fun names() = if (Random().nextBoolean()) "Elvis" else "Presley" val shortName = names() .takeIf { it.length )* 5 } +, "Too long" val longName = names() .takeUnless { it.length )* 5 } +, "Too Short"
  • 10. class DeepLinkParser { fun parse(uri : String) : ProductId { // Parse your URI and extract product id } }
  • 11. class DeepLinkHandler( val parser: DeepLinkParser) { operator fun invoke(url : String) : Intent { // Handle with parser and get your Intent } }
  • 12. class DeepLinkHandler( val parser: DeepLinkParser) { operator fun invoke(url : String) : Intent { // Handle with parser and get your Intent } }
  • 13. Invoking Instances val parser = DeepLinkParser() val handler = DeepLinkHandler(parser) val intent = handler("myapp:-.product/123456") // Launch your Activity 🚀
  • 14. A tiny web DSL sealed class HTTPMethod object GET : HTTPMethod() object POST : HTTPMethod() class Status { var code: Int = 0 var payload: String = "" } class HttpRequest { var method: HTTPMethod = GET var body: String = "" var query: String = "" } class HttpResponse { var internalMessage: String = "" lateinit var status: Status }
  • 15. class Endpoint { lateinit var request: HttpRequest lateinit var response: HttpResponse fun handle() { -. TODO } }
  • 16. fun endpoint( path: String, block: Endpoint.() '( Unit) = Endpoint().apply { block() }.handle() endpoint("/api/product") { }
  • 17. class Endpoint { lateinit var request: HttpRequest lateinit var response: HttpResponse fun request(block: HttpRequest.() '( Unit) { request = HttpRequest().apply { block() } } fun response(block: HttpResponse.() '( Unit) { response = HttpResponse().apply { block() } } fun handle() { -. TODO } } endpoint("/api/product") { request { method = POST, body = "{ Some json }" } response { } }
  • 18. endpoint("/api/product") { request { method = POST, body = "{ Some json }" } response { status { code = 200 payload = "{ Some json }" } } } class HttpResponse { var internalMessage: String = "" lateinit var status: Status fun status(setup: Status.() '( Unit) { status = Status().apply { setup() } } }
  • 19. endpoint("/api/product") { request { method = POST, body = "{ Some json }" } response { status { code = 200 payload = "{ Some json }" } } } Can we do better ? đŸ€”
  • 20. class Endpoint { lateinit var request: HttpRequest lateinit var response: HttpResponse fun request(block: HttpRequest.() '( Unit) { request = HttpRequest().apply { block() } } fun response(block: HttpResponse.() '( Unit) { response = HttpResponse().apply { block() } } fun handle() { -. TODO } }
  • 21. class Endpoint { lateinit var request: HttpRequest lateinit var response: HttpResponse fun request(block: HttpRequest.() '( Unit) { request = HttpRequest().apply { block() } } fun response(block: HttpResponse.() '( Unit) { response = HttpResponse().apply { block() } } fun handle() { -. TODO } } 👀
  • 22. class Endpoint { lateinit var request: HttpRequest lateinit var response: HttpResponse fun request(block: HttpRequest.() '( Unit) { request = HttpRequest().apply { block() } } fun response(block: HttpResponse.() '( Unit) { response = HttpResponse().apply { block() } } fun handle() { -. TODO } } class HttpResponse { var internalMessage: String = "" lateinit var status: Status fun status(setup: Status.() '( Unit) { status = Status().apply { setup() } } }
  • 23. class Endpoint { lateinit var request: HttpRequest lateinit var response: HttpResponse fun request(block: HttpRequest.() '( Unit) { request = HttpRequest().apply { block() } } fun handle() { -. TODO } } class HttpResponse { var internalMessage: String = "" lateinit var status: Status operator fun invoke( setup: Status.() -> Unit) { status = Status().apply { setup() } } }
  • 24. endpoint("/api/product") { request { method = POST body = "{ Some json }" } response { code = 200 payload = "{ Some json }" } } endpoint("/api/product") { request { method = POST, body = "{ Some json }" } response { status { code = 200 payload = "{ Some json }" } } } Before After
  • 27.
  • 28. interface FormValidator { fun validate(name: String?): Boolean } class FormPresenter { private companion object : FormValidator { override fun validate(name: String?) = name/0isNotEmpty() +, throw IllegalArgumentException("Invalid Name") } }
  • 29. interface FormValidator { fun validate(name: String?): Boolean } class FormPresenter { private companion object : FormValidator { override fun validate(name: String?) = name/0isNotEmpty() +, throw IllegalArgumentException("Invalid Name") } }
  • 30. Fake Constructors val sampa = Location("23.5505° S", "46.6333° W") data class Location( val latitude: Float, val longitude: Float ) đŸ€”
  • 31. data class Location( val latitude: Float, val longitude: Float) { companion object { operator fun invoke(lat: String, long: String) = Location(parse(lat), parse(long)) private fun parse(coordinate: String): Float { -. convert the String representation } } }
  • 32. data class Location( val latitude: Float, val longitude: Float) { companion object { operator fun invoke(lat: String, long: String) = Location(parse(lat), parse(long)) private fun parse(coordinate: String): Float { -. convert the String representation } } }
  • 34. The Nothing Type https://en.wikipedia.org/wiki/Bottom_type " In type theory, a theory within mathematical logic, the bottom type is the type that has no values. It is also called the zero or empty type, and is sometimes denoted with falsum (⊄). A function whose return type is bottom cannot return any value. In the Curry–Howard correspondence, the bottom type corresponds to falsity. "
  • 35. /#$ * The type with only one value: the Unit object. * This type corresponds to the `void` type * in Java. %& public object Unit { override fun toString() = "kotlin.Unit" }
  • 37. /#$ * Always throws [NotImplementedError] * stating that operation is not implemented. %& @kotlin.internal.InlineOnly public inline fun TODO(): Nothing = throw NotImplementedError()
  • 38.
  • 39. Nothing and ïŹ‚ow control inline fun <T> guard( receiver: T?, block: () '( Nothing): T { if (receiver 12 null) { block() } return receiver } https://gist.github.com/hzsweers/463500043b1a9708ba4e26c7ad1862fd
  • 40. fun guarding() { val conference: String? = "Kotlin Summit" val guarded = guard(conference) { return } val guardedAgain = guard(conference) { throw IllegalStateException("Null konf") } val invalid = guard(conference) { -.Compiler error because not -.returned or thrown an exception! } }
  • 41. Nothing and Generics sealed class Tree<out T> class Node<T>( val left: Tree<T>, val right: Tree<T>) : Tree<T>() class Leaf<T>(val value: T) : Tree<T>() object Empty : Tree<Nothing>()
  • 42. val tree = Node( Leaf("1"), Node( Leaf("2"), Empty ) ) 1 2
  • 43. sealed class Result<out V, out E> data class Value<out V>(val value: V) : Result<V, Nothing>() data class Error<out E>(val error: E) : Result<Nothing, E>()
  • 45. interface Validation { fun validate(input: String): Boolean } class NameValidator : Validation { override fun validate(input: String) = input.isNotEmpty() 34 input.length 56 2 } Class delegation
  • 46. val accepted = FormViewModel().validate("Bira") class FormViewModel : Validation by NameValidator() Class delegation
  • 47. class FormViewModel : FormValidator by Internal { companion object Internal : FormValidator { override fun validate(name: String?) = name/0isNotEmpty()+, false } } val rejected = FormViewModel().validate("Hi")
  • 48. class CheckProïŹle { companion object : (Int) '( Boolean by ShouldBeLegal } val canDrink = CheckProïŹle(35) object ShouldBeLegal : (Int) '( Boolean { override fun invoke(age: Int) = age 5618 }
  • 49. interface HandleSuccess { fun showResult() } interface HandleError { fun showError() } interface LoginScreen : HandleSuccess, HandleError interface ProductScreen : HandleSuccess, HandleError
  • 50. Selective delegation fun <C> performOperation(behavior: C) where C : HandleSuccess, C : HandleError { try { executeSomething() behavior.showResult() } catch (error: Throwable) { behavior.showError() } }
  • 51. Selective delegation fun <C> performOperation(behavior: C) where C : HandleSuccess, C : HandleError { try { executeSomething() behavior.showResult() } catch (error: Throwable) { behavior.showError() } }
  • 53. What if I told you that extensions are not only for objects ???
  • 54. val checkLegalAge: (Int) '( Boolean = { it 56 18 } val checkNotDead: (Int) '( Boolean = { it < 150 } fun ((Int) '( Boolean).report(age: Int) = this.invoke(age) .also { print((if (it) "Ok" else "Not OK")) } fun misjudge(age: Int) = if (age > 15) checkLegalAge.report(age) else checkNotDead.invoke(age)
  • 55.
  • 56. Final Remarks Kotlin has it's secrets, go explore !!! Learn more hidden features for fun and proïŹt
  • 58. UBIRATAN SOARES Computer Scientist by ICMC/USP Software Engineer, curious guy Google Developer Expert for Android / Kotlin Teacher, speaker, etc, etc