In this talk I presented three important topics in Kotlin Standard Library: Scope Functions (let, apply, also, run and with); Annotations (Deprecated, Experimental, Jvm*, DslMarker); and Delegates (lazy, vetoable, observable)
Aplicações assíncronas no Android com Coroutines & JetpackNelson Glauber Leal
The document discusses asynchronous applications in Android using Coroutines & Jetpack. It introduces coroutines as lightweight threads that make asynchronous programming easier by replacing callbacks with suspending functions. It covers key coroutine concepts like Job, Context, Scope and Dispatcher. It also discusses how coroutines can be used with Lifecycle, ViewModel and WorkManager components in Jetpack to build asynchronous Android applications.
Aplicações Assíncronas no Android com Coroutines e JetpackNelson Glauber Leal
Para usufruir dos múltiplos núcleos existentes nos processadores dos smartphones atuais, podemos realizar chamadas assíncronas de modo a paralelizar o fluxo de execução da aplicação. Normalmente isso é feito por meio de threads e callbacks que acabam por adicionar uma complexidade ao código que pode comprometer sua leitura e manutenção. Nessa apresentação, veremos como utilizar a API de Coroutines do Kotlin em conjunto com diversas bibliotecas do Jetpack do Android de modo a implementar programação assíncrona forma simples e eficiente.
Aplicações assíncronas no Android com Coroutines & JetpackNelson Glauber Leal
Slides da minha apresentação realizada no Meetup do GDG Salvador em 02/05/2020.
https://www.meetup.com/gdg-salvador/events/270221209/
This document provides an overview of the Go programming language including:
- A brief history of Go from its origins at Google in 2007 to current widespread usage.
- Key features of Go like functions, structs, interfaces, methods, slices, pointers, go-routines and channels.
- Examples of basic Go code demonstrating functions, structs, methods, interfaces, concurrency with go-routines and channels.
- Discussion of things missing from Go like classes, generics and exceptions.
- Quotes from developers commenting both positively and negatively on Go's simplicity and tradeoffs.
- Links to further resources like the Go tour to learn more.
This document discusses Python technologies used at Douban. It describes how Python is used for web development, including frameworks like Quixote and tools like Mako templates. It also discusses using Python for system tasks like caching with cmemcached, profiling code, and interacting with databases. Overall Python allows Douban to build scalable web applications and services.
This document summarizes an advanced Python programming course, covering topics like performance tuning, garbage collection, and extending Python. It discusses profiling Python code to find bottlenecks, using more efficient algorithms and data structures, optimizing code through techniques like reducing temporary objects and inline functions, leveraging faster tools like NumPy, writing extension modules in C, and parallelizing computation across CPUs and clusters. It also explains basic garbage collection algorithms like reference counting and mark-and-sweep used in CPython.
Room is an Android framework that provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite. It provides entities, data access objects (DAOs), and a database class to simplify data persistence. Key aspects include using annotations to define entities and SQL operations, verifying SQL at compile time, supporting relationships between entities and migrations. Room also integrates with LiveData and RxJava for observable data streams.
The document discusses functional programming concepts in Swift such as functors, monads, and higher-order functions. It provides examples of how to use functions like map, flatMap, filter and reduce to transform collections. It also discusses topics like cognitive complexity, pure functions, and how functors are containers that can be mapped while monads support flatMapping to flatten nested collections.
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
OneRing is a desktop application platform that allows building desktop applications using web technologies like HTML, CSS, and JavaScript. It uses QtWebKit to render web content and exposes a C API and Python bindings to register and run web-based applications as native desktop apps. OneRing-based apps can access native GUI widgets and OS services and are distributed and updated like regular desktop programs.
Feel of Kotlin (Berlin JUG 16 Apr 2015)intelliyole
Kotlin is a statically typed programming language that targets the JVM, Android and web. It has been in development since 2010 by JetBrains. Kotlin code is concise, expressive and safe to develop with. It is interoperable with Java code and has equivalent performance, with a smooth learning curve that maintains existing Java investments. JetBrains uses Kotlin in their own products and tools. The document provides examples of Kotlin features like classes, traits, null safety, extension functions, operator overloading, and HTML builders.
The document defines a LineChart class that extends the Chart class. The LineChart class constructor calls the parent constructor and draws the chart. The draw method builds a line chart from the series data using an SVG library, appends it to the canvas, and adds statistics for each data point by calling the parent addStats method. The getSerieData static method calculates max and average values for a data series. The class is exported for use in other code.
This document introduces ClojureScript and building applications with it. It discusses how ClojureScript compiles Clojure to JavaScript and can run anywhere JavaScript runs. It covers the basics of the ClojureScript language like syntax, data structures, and functions. It also discusses tools for ClojureScript development like Leiningen, Figwheel, Shadow CLJS, and Cursive. Additionally, it covers building web applications with ClojureScript using templates like Hiccup and libraries like Reagent and Reframe.
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
Kotlin Coroutines Flow is coming to provide a cold asynchronous data stream that emits values sequentially within a coroutine. Flow allows mapping, filtering, and collecting values, handles exceptions transparently, and preserves context. It can integrate with existing APIs like Room and Retrofit using adapters, and is the primary way to handle async streams going forward. Channels will still be used for hot streams and synchronization between coroutines.
My JSConf.eu talk about next-gen JavaScript metaprogramming features, starting with ES5's new Object APIs and then focusing on the forthcoming Proxy object, approved for the next ECMA-262 Edition. This is beautiful work from Tom Van Cutsem and Mark Miller, with Andreas Gal helping on the implementation front -- proxies are already shipping in Firefox 4 betas.
Generators in ECMAScript provide a way to write iterator functions using the yield keyword. This allows for writing functions that can be iterated over manually or used to create infinite streams. Generators also enable asynchronous programming using coroutines instead of callbacks. They allow for cooperative multitasking by starting multiple generator functions as "threads" that yield values in a nondeterministic order. Array comprehensions are also proposed as a shorthand for transforming arrays using generators.
The document discusses using ES6 features in real-world applications. It provides examples of using arrow functions, classes, destructuring, template literals, and default parameters to write cleaner code. It also discusses tools for enabling ES6 features that are not yet fully supported, such as transpilers, and flags in Node.js and Chrome to enable more experimental features. Overall, the document advocates adopting ES6 features that make code more concise and readable.
This document compares several JVM languages including Java, Scala, Groovy, Kotlin, Clojure and Ceylon. It discusses their classification as functional or object-oriented, static or dynamic typing. It also summarizes key features of each language such as support for functional programming paradigms, closures, immutable data structures, and parallel processing capabilities. The document provides code examples to illustrate concepts in Scala, Kotlin, and Groovy.
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
Kotlin Coroutines provide a new way to write asynchronous and concurrent code using suspending functions and structured concurrency. Coroutines avoid callbacks and allow sequencing of asynchronous code using async/await. Coroutines are lightweight threads that can be suspended and resumed. Channels allow coroutines to communicate and share data. Flows provide a reactive streams API for coroutines. Kotlin coroutines offer improvements over other asynchronous programming models like callbacks and RxJava.
This document provides a history of ECMAScript (ES) and JavaScript standards. It discusses the origins of JavaScript in 1995 and its standardization by ECMA in 1997 as ECMAScript. New versions were released periodically, including ES5 in 2009 and ES6 in 2015. ES6 was also referred to as ES2015 since version names going forward would be based on the year of release.
Kotlin is a better alternative to Java that fixes many of Java's weaknesses. It removes unnecessary syntax like semicolons and checked exceptions, adds powerful features like type inference, lambdas, and when expressions, and compiles to JVM bytecode so it can interoperate with existing Java code and libraries. Kotlin is fully supported by JetBrains and can also target JavaScript, making it a practical and modern option for JVM development.
Intro to Reactive Thinking and RxJava 2JollyRogers5
Reactive Extensions (Rx) was first introduced by Microsoft in 2009 and has since been ported to most platforms and languages. It provides a way to model asynchronous data streams and events using Observables in a way that makes it easier to compose asynchronous and event-based programs. Some key advantages include simplifying asynchronous operations, surfacing errors sooner, and reducing bugs from state variables. However, the API is large so there is a steep learning curve. RxJava is an implementation of Rx for the JVM that allows pushing data instead of pulling it without worrying about threads. Common operators like map, filter, and flatMap allow transforming and combining Observable streams.
Here are the key points about GRASP patterns:
1. GRASP stands for General Responsibility Assignment Software Patterns. It is a set of 9 patterns used to assign responsibilities to classes in object-oriented design.
2. Properly assigning responsibilities and distributing them among classes is a core part of object-oriented design. Developers and designers should be familiar with these patterns.
3. The 9 GRASP patterns are: Information Expert, Creator, Controller, Low Coupling, High Cohesion, Indirection, Polymorphism, Pure Fabrication, and Protected Variations. Each pattern provides guidance on distributing responsibilities in a certain context.
4. When designing a system, analyzing which classes should have which responsibilities based
This document provides a history of JavaScript and ECMAScript specifications from 1995 to the present. It discusses the standardization process and key people and organizations involved like B. Eich, TC39, and ECMA. Major versions and proposed features are summarized, including ES6/ES2015 additions like arrow functions, block scoping with let/const, classes, modules, iterators/generators, and proxies.
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
JavaScript is single threaded, so understanding the async patterns available in the language is critical to creating maintainable NodeJS applications with good performance. In order to master “thinking in async”, we’ll explore the async patterns available in node and JavaScript including standard callbacks, promises, thunks/tasks, the new async/await, the upcoming asynchronous iteration features, streams, CSP and ES Observables.
The Ring programming language version 1.7 book - Part 35 of 196Mahmoud Samir Fayed
The document contains documentation for the Ring programming language. It describes a Ring class that stores information about objects, including their name, symbol, and position. For each object, it lists these attributes. It also contains descriptions of using self and this to reference attributes and methods from within classes.
[Codemotion 2015] patrones de diseño con java8Alonso Torres
Presentada en el Codemotion Madrid 2015.
Abstract:
Han pasado más de 20 años desde la publicación del famoso libro "Patrones de diseño" por el grupo conocido como "Gang of Four".
Durante años, estos patrones han mantenido su actualidad por ser lo suficientemente genéricos para todo tipo de software y resolver problemas comunes de diseño de las aplicaciones que desarrollamos a diario.
Pero algo ha cambiado con Java 8.
Con las nuevas características de Java 8, y en especial las lambdas, es necesario revisitar estos famosos patrones para adaptarlos a sus nuevas funcionalidades.
En esta charla repasaremos algunos de los famosos patrones viendo como adaptarlos a las nuevas características de Java. Además, podremos ver como mejorar nuestro tradicional diseño orientado a objetos gracias a las lambdas y a la programación funcional.
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
OneRing is a desktop application platform that allows building desktop applications using web technologies like HTML, CSS, and JavaScript. It uses QtWebKit to render web content and exposes a C API and Python bindings to register and run web-based applications as native desktop apps. OneRing-based apps can access native GUI widgets and OS services and are distributed and updated like regular desktop programs.
Feel of Kotlin (Berlin JUG 16 Apr 2015)intelliyole
Kotlin is a statically typed programming language that targets the JVM, Android and web. It has been in development since 2010 by JetBrains. Kotlin code is concise, expressive and safe to develop with. It is interoperable with Java code and has equivalent performance, with a smooth learning curve that maintains existing Java investments. JetBrains uses Kotlin in their own products and tools. The document provides examples of Kotlin features like classes, traits, null safety, extension functions, operator overloading, and HTML builders.
The document defines a LineChart class that extends the Chart class. The LineChart class constructor calls the parent constructor and draws the chart. The draw method builds a line chart from the series data using an SVG library, appends it to the canvas, and adds statistics for each data point by calling the parent addStats method. The getSerieData static method calculates max and average values for a data series. The class is exported for use in other code.
This document introduces ClojureScript and building applications with it. It discusses how ClojureScript compiles Clojure to JavaScript and can run anywhere JavaScript runs. It covers the basics of the ClojureScript language like syntax, data structures, and functions. It also discusses tools for ClojureScript development like Leiningen, Figwheel, Shadow CLJS, and Cursive. Additionally, it covers building web applications with ClojureScript using templates like Hiccup and libraries like Reagent and Reframe.
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
Kotlin Coroutines Flow is coming to provide a cold asynchronous data stream that emits values sequentially within a coroutine. Flow allows mapping, filtering, and collecting values, handles exceptions transparently, and preserves context. It can integrate with existing APIs like Room and Retrofit using adapters, and is the primary way to handle async streams going forward. Channels will still be used for hot streams and synchronization between coroutines.
My JSConf.eu talk about next-gen JavaScript metaprogramming features, starting with ES5's new Object APIs and then focusing on the forthcoming Proxy object, approved for the next ECMA-262 Edition. This is beautiful work from Tom Van Cutsem and Mark Miller, with Andreas Gal helping on the implementation front -- proxies are already shipping in Firefox 4 betas.
Generators in ECMAScript provide a way to write iterator functions using the yield keyword. This allows for writing functions that can be iterated over manually or used to create infinite streams. Generators also enable asynchronous programming using coroutines instead of callbacks. They allow for cooperative multitasking by starting multiple generator functions as "threads" that yield values in a nondeterministic order. Array comprehensions are also proposed as a shorthand for transforming arrays using generators.
The document discusses using ES6 features in real-world applications. It provides examples of using arrow functions, classes, destructuring, template literals, and default parameters to write cleaner code. It also discusses tools for enabling ES6 features that are not yet fully supported, such as transpilers, and flags in Node.js and Chrome to enable more experimental features. Overall, the document advocates adopting ES6 features that make code more concise and readable.
This document compares several JVM languages including Java, Scala, Groovy, Kotlin, Clojure and Ceylon. It discusses their classification as functional or object-oriented, static or dynamic typing. It also summarizes key features of each language such as support for functional programming paradigms, closures, immutable data structures, and parallel processing capabilities. The document provides code examples to illustrate concepts in Scala, Kotlin, and Groovy.
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
Kotlin Coroutines provide a new way to write asynchronous and concurrent code using suspending functions and structured concurrency. Coroutines avoid callbacks and allow sequencing of asynchronous code using async/await. Coroutines are lightweight threads that can be suspended and resumed. Channels allow coroutines to communicate and share data. Flows provide a reactive streams API for coroutines. Kotlin coroutines offer improvements over other asynchronous programming models like callbacks and RxJava.
This document provides a history of ECMAScript (ES) and JavaScript standards. It discusses the origins of JavaScript in 1995 and its standardization by ECMA in 1997 as ECMAScript. New versions were released periodically, including ES5 in 2009 and ES6 in 2015. ES6 was also referred to as ES2015 since version names going forward would be based on the year of release.
Kotlin is a better alternative to Java that fixes many of Java's weaknesses. It removes unnecessary syntax like semicolons and checked exceptions, adds powerful features like type inference, lambdas, and when expressions, and compiles to JVM bytecode so it can interoperate with existing Java code and libraries. Kotlin is fully supported by JetBrains and can also target JavaScript, making it a practical and modern option for JVM development.
Intro to Reactive Thinking and RxJava 2JollyRogers5
Reactive Extensions (Rx) was first introduced by Microsoft in 2009 and has since been ported to most platforms and languages. It provides a way to model asynchronous data streams and events using Observables in a way that makes it easier to compose asynchronous and event-based programs. Some key advantages include simplifying asynchronous operations, surfacing errors sooner, and reducing bugs from state variables. However, the API is large so there is a steep learning curve. RxJava is an implementation of Rx for the JVM that allows pushing data instead of pulling it without worrying about threads. Common operators like map, filter, and flatMap allow transforming and combining Observable streams.
Here are the key points about GRASP patterns:
1. GRASP stands for General Responsibility Assignment Software Patterns. It is a set of 9 patterns used to assign responsibilities to classes in object-oriented design.
2. Properly assigning responsibilities and distributing them among classes is a core part of object-oriented design. Developers and designers should be familiar with these patterns.
3. The 9 GRASP patterns are: Information Expert, Creator, Controller, Low Coupling, High Cohesion, Indirection, Polymorphism, Pure Fabrication, and Protected Variations. Each pattern provides guidance on distributing responsibilities in a certain context.
4. When designing a system, analyzing which classes should have which responsibilities based
This document provides a history of JavaScript and ECMAScript specifications from 1995 to the present. It discusses the standardization process and key people and organizations involved like B. Eich, TC39, and ECMA. Major versions and proposed features are summarized, including ES6/ES2015 additions like arrow functions, block scoping with let/const, classes, modules, iterators/generators, and proxies.
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
JavaScript is single threaded, so understanding the async patterns available in the language is critical to creating maintainable NodeJS applications with good performance. In order to master “thinking in async”, we’ll explore the async patterns available in node and JavaScript including standard callbacks, promises, thunks/tasks, the new async/await, the upcoming asynchronous iteration features, streams, CSP and ES Observables.
The Ring programming language version 1.7 book - Part 35 of 196Mahmoud Samir Fayed
The document contains documentation for the Ring programming language. It describes a Ring class that stores information about objects, including their name, symbol, and position. For each object, it lists these attributes. It also contains descriptions of using self and this to reference attributes and methods from within classes.
[Codemotion 2015] patrones de diseño con java8Alonso Torres
Presentada en el Codemotion Madrid 2015.
Abstract:
Han pasado más de 20 años desde la publicación del famoso libro "Patrones de diseño" por el grupo conocido como "Gang of Four".
Durante años, estos patrones han mantenido su actualidad por ser lo suficientemente genéricos para todo tipo de software y resolver problemas comunes de diseño de las aplicaciones que desarrollamos a diario.
Pero algo ha cambiado con Java 8.
Con las nuevas características de Java 8, y en especial las lambdas, es necesario revisitar estos famosos patrones para adaptarlos a sus nuevas funcionalidades.
En esta charla repasaremos algunos de los famosos patrones viendo como adaptarlos a las nuevas características de Java. Además, podremos ver como mejorar nuestro tradicional diseño orientado a objetos gracias a las lambdas y a la programación funcional.
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
The document discusses several Kotlin advanced topics including delegated properties, lazy properties, objects, higher-order functions, lambdas, inline functions, and standard library functions like apply, also, let. It explains concepts like lazy initialization with lazy properties, property delegation, object expressions and declarations, functional programming with higher-order functions and lambdas, and inline functions for performance. It also covers utility functions in the standard library for working with objects and collections.
This document discusses the history and evolution of functional programming in Java, including lambda expressions and streams. It describes how lambda expressions allow passing behaviors as arguments to methods like normal data. This improves API design, opportunities for optimization, and code readability. Streams encourage a lazy, pipelined style and can execute operations in parallel. Functional idioms like immutability and pure functions help enforce correctness and isolation of side effects.
C++ is an object-oriented programming language that is an extension of C. It was developed in the early 1980s by Bjarne Stroustrup at Bell Labs. C++ supports concepts like inheritance, polymorphism, and encapsulation that make it suitable for large, complex programs. Inheritance allows classes to inherit properties from parent classes. Polymorphism is the ability to process objects of different types in the same way. Encapsulation combines data and functions that operate on that data within a single unit, hiding implementation details. File input/output in C++ can be handled through streams like ifstream for input and ofstream for output.
Kotlin provides a modern, statically-typed, and expressive alternative to Java, offering null safety, coroutines for asynchronous programming, and a succinct, intuitive syntax.
This presentation will give an introduction to Kotlin, looking at various language features, how those features are utilized by the Kotlin Standard Library, and how they are implemented in performance-conscious ways.
Object- objects have states and behaviors. Example: A dog has states-color, name, breed , as well as behaviors – barking, eating. An object is an instance of a class.
Class- A class can be defined as a template/blue print that describe the behavior/states that object of its type support.
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
Have you ever used PHP's built in reflection, only to find you can't do quite what you wanted? What about finding types for parameters or properties? What about reflecting on classes that aren't loaded, so that you can modify them directly?
Better Reflection is an awesome new library that uses magical time-warp techniques* (*actual magic or time-warp not guaranteed) to improve on PHP's built-in reflection by providing additional functionality. In this talk we'll cover what reflection is all about, explore the cool features of Better Reflection already implemented, the difficulties we faced actually writing the thing, and how you can use Better Reflection in your projects to maximise your reflection-fu.
Java 8 introduced several new features including lambda expressions, which allow functional-style programming in Java through functional interfaces containing a single abstract method, streams, which provide a way to process collections of objects in a declarative way, and default and static methods in interfaces to enable multiple inheritance. The document provides examples of using these new Java 8 features such as lambda expressions, functional interfaces, streams, and default and static methods in interfaces.
1. Generics in Java allow types (like lists and stacks) to operate on multiple type parameters, providing compile-time type safety without sacrificing performance.
2. Using generics avoids casting and reduces errors by catching type problems at compile time rather than runtime. It produces more readable and maintainable code.
3. The document demonstrates how to define a generic Stack class that works for any type rather than just Integers, avoiding code duplication and future bugs.
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
The document provides information about various Python concepts like print statement, variables, data types, operators, conditional statements, loops, functions, modules, exceptions, files and packages. It explains print statement syntax, how variables work in Python, built-in data types like numbers, strings, lists, dictionaries and tuples. It also discusses conditional statements like if-else, loops like while and for, functions, modules, exceptions, file handling operations and packages in Python.
This document provides an introduction and overview of the Kotlin programming language. It covers key Kotlin concepts and features such as properties, null safety, classes, interfaces, extensions, and collections. It also includes Kotlin's timeline, development tools, and basic data types. The agenda outlines topics like String templates, OOP concepts, lambdas, and infix notation that are explained further in the document.
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
Kotlin is a powerful language, but it also comes with its traps and pitfalls. This presentation is about uncovering the very nice features and strange particularities that the language has to offer.
Stuck with your Ruby Programming Assignment. Get 24/7 help from tutors with Phd in the subject. Email us at [email protected]
Reach us at http://www.HelpWithAssignment.com
Get 24/7 Reliable Ruby programming Assignment Help, 100% error free, money back guarantee, Phd level tutors, A grade guarantee, www.HelpwithAssignment.com or email us at [email protected]
The document discusses Groovy, an object-oriented scripting language for the Java Virtual Machine (JVM). It provides examples of Groovy code and describes Groovy's features such as optional typing, closures, list and map syntax, and interoperability with Java. Key features include dynamic typing, closures/anonymous functions, built-in support for lists/maps, and compiling to Java bytecode. Groovy aims to make Java development more productive and agile through a syntax resembling Python/Ruby.
Java 8 introduced several new features including lambda expressions, functional interfaces, and streams to support functional programming. Interfaces can now contain default and static methods to allow multiple inheritance. Streams provide a way to process collections of data elements sequentially and support parallel processing.
This document provides an overview of functional programming patterns and abstractions in Java 8. It introduces common functional concepts like functors, applicative functors, monads, and type classes. It then describes implementations of these concepts for option, either, stream, future, and completable future in Java. The document explains how functional patterns allow for simpler composition and avoidance of null checks compared to imperative programming with conditionals.
This document discusses how Kotlin can help improve Android app quality by eliminating common issues like crashes and null pointer exceptions. It highlights Kotlin features like non-nullable types, the safe call operator, and extension functions. Kotlin offers improvements over Java like optional and collection APIs without nullability and verbosity issues. It also maintains full interoperability with Java while providing better tools for static analysis and debugging.
This document provides information about Javier Eguiluz, a programmer and trainer from Spain who specializes in Symfony and Twig. It outlines his experience with Symfony and as the author of a popular Symfony book. The agenda covers tips, tricks, advanced features, best practices and new noteworthy features of the Twig templating engine.
Nessa apresentação falei sobre as principais novidades do Android apresentadas no Google I/O 2024. Incluindo: Gemini, Adaptive Apps, Android 15, Segurança, Compose, Performance, Kotlin, KMP, etc.
O documento discute boas práticas de desenvolvimento para aplicativos Android em telas grandes, incluindo a importância de se preocupar com a arquitetura, adaptação para diferentes tamanhos de tela e configurações de dispositivo, e formas de garantir a continuidade da experiência do usuário.
1. O documento resume as principais novidades do Android em 2023 anunciadas na conferência Google I/O, incluindo melhorias no Jetpack Compose como novos componentes, desempenho e bibliotecas.
2. Também apresenta novas funcionalidades para telas grandes como adaptação de apps, práticas recomendadas e ferramentas de teste.
3. O documento discute formas de lidar com mudanças de configuração e recriação de activities para manter o estado da aplicação, como View Model, Data Store e Saved State APIs.
O documento resume as principais novidades das bibliotecas do Jetpack. O Jetpack ajuda desenvolvedores a seguir boas práticas e escrever código consistente para Android. As bibliotecas CameraX, DataStore, WorkManager e outras receberam melhorias de desempenho e novas funcionalidades. O documento também destaca integrações entre Jetpack e Compose para facilitar o desenvolvimento em Android.
Jetpack Compose is a new declarative UI toolkit from Google that uses Kotlin to simplify and accelerate Android UI development with less code. It uses a declarative paradigm where the UI and its state are defined together, rather than imperatively updating views. Jetpack Compose is currently in beta but aims to provide a modern way to build user interfaces in Android with composable UI components instead of traditional screens.
Jetpack Compose is the new Android UI framework that allows you to create rich user interfaces in a declarative way using Kotlin language. In this presentation, it will be demonstrated how to take the first steps with Compose, learn its main concepts and understand how to be prepared for this change of paradigm on the front-end development of native Android applications.
O documento fornece uma introdução abrangente sobre desenvolvimento para Android, cobrindo tópicos como: o que é Android, sua história, linguagens de programação, arquitetura, ferramentas, desafios e oportunidades na área.
Nessa apresentação demonstro como arquitetar uma aplicação Android utilizando MVVM+Clean Architecture no Android utilizando as bibliotecas do Jetpack (View Model, Room, LiveData, ...)
Nessa apresentação demonstro como arquitetar uma aplicação Android utilizando as bibliotecas do Jetpack. O exemplo apresentado utiliza MVVM+Clean:
- Na camada de dados local, Room com Coroutines e Flow;
- View Model, Live Data e Data Binding na camada de apresentação;
- Fragments com a Navigation API na camada de UI.
O app também conta com uma implementação de banco de dados remoto utilizando Firebase.
Aplicações assíncronas no Android com Coroutines & JetpackNelson Glauber Leal
Para usufruir dos múltiplos núcleos existentes nos processadores dos smartphones atuais, podemos realizar chamadas assíncronas de modo a paralelizar o fluxo de execução da aplicação. Normalmente isso é feito por meio de threads e callbacks que acabam por adicionar uma complexidade ao código que pode comprometer sua leitura e manutenção. Nessa apresentação, veremos como utilizar a API de Coroutines do Kotlin em conjunto com diversas bibliotecas do Jetpack do Android de modo a implementar programação assíncrona forma simples e eficiente.
Slides da apresentação no Meetup realizado no dia 13/04/2019 no CESAR.school, onde foi apresentada uma introdução ao desenvolvimento Android com Kotlin
Nessa apresentação demonstro como aplicar alguns dos Architecture Components disponíveis no Jetpack em uma arquitetura que segue o padrão Clean com MVVM.
Palestra apresentada no The Developers Conference São Paulo 2018 na Trilha Android.
A ideia dessa apresentação é dar uma visão geral sobre os principais tópicos do desenvolvimento Android utilizados atualmente, tais como: Kotlin, MVP, MVVM, Architecture Components, ConstraintLayout, RXJava, Firebase e testes.
Palestra realizada no DevFestXP em Recife (09/12/2017) apresentando as principais técnicas, APIs e ferramentas mais atuais utilizadas no desenvolvimento de aplicações Android
Slides da minha palestra sobre Constraint Layout apresentada no Android Dev Conference 2017.
Código-fonte disponível em:
https://github.com/nglauber/ConstraintLayoutAndroidDevConf2017
São Paulo, 25 de Agosto de 2017.
Palestra sobre persistência de dados no SQLite com Room API apresentada no TDC São Paulo 2017 (19/07/2017). O Room é um dos Architectural Components apresentados pelo Google no Google I/O 2017.
Palestra apresentada no evento de comemoração dos 4 anos do meetup de Android do GDG São Paulo. Oxigênio aceleradora no dia 10/Jun/2017
O código-fonte dos exemplos está disponível em:
https://github.com/nglauber/playground/tree/master/android/AnimationDemo
PRTG Network Monitor Crack Latest Version & Serial Key 2025 [100% Working]saimabibi60507
Copy & Past Link 👉👉
https://dr-up-community.info/
PRTG Network Monitor is a network monitoring software developed by Paessler that provides comprehensive monitoring of IT infrastructure, including servers, devices, applications, and network traffic. It helps identify bottlenecks, track performance, and troubleshoot issues across various network environments, both on-premises and in the cloud.
Top 10 Data Cleansing Tools for 2025.pdfAffinityCore
Discover the top 10 data cleansing tools for 2025, designed to help businesses clean, transform, and enhance data accuracy. Improve decision-making and data quality with these powerful solutions.
Societal challenges of AI: biases, multilinguism and sustainabilityJordi Cabot
Towards a fairer, inclusive and sustainable AI that works for everybody.
Reviewing the state of the art on these challenges and what we're doing at LIST to test current LLMs and help you select the one that works best for you
Landscape of Requirements Engineering for/by AI through Literature ReviewHironori Washizaki
Hironori Washizaki, "Landscape of Requirements Engineering for/by AI through Literature Review," RAISE 2025: Workshop on Requirements engineering for AI-powered SoftwarE, 2025.
WinRAR Crack for Windows (100% Working 2025)sh607827
copy and past on google ➤ ➤➤ https://hdlicense.org/ddl/
WinRAR Crack Free Download is a powerful archive manager that provides full support for RAR and ZIP archives and decompresses CAB, ARJ, LZH, TAR, GZ, ACE, UUE, .
F-Secure Freedome VPN 2025 Crack Plus Activation New Versionsaimabibi60507
Copy & Past Link 👉👉
https://dr-up-community.info/
F-Secure Freedome VPN is a virtual private network service developed by F-Secure, a Finnish cybersecurity company. It offers features such as Wi-Fi protection, IP address masking, browsing protection, and a kill switch to enhance online privacy and security .
Why Orangescrum Is a Game Changer for Construction Companies in 2025Orangescrum
Orangescrum revolutionizes construction project management in 2025 with real-time collaboration, resource planning, task tracking, and workflow automation, boosting efficiency, transparency, and on-time project delivery.
Cryptocurrency Exchange Script like Binance.pptxriyageorge2024
This SlideShare dives into the process of developing a crypto exchange platform like Binance, one of the world’s largest and most successful cryptocurrency exchanges.
Who Watches the Watchmen (SciFiDevCon 2025)Allon Mureinik
Tests, especially unit tests, are the developers’ superheroes. They allow us to mess around with our code and keep us safe.
We often trust them with the safety of our codebase, but how do we know that we should? How do we know that this trust is well-deserved?
Enter mutation testing – by intentionally injecting harmful mutations into our code and seeing if they are caught by the tests, we can evaluate the quality of the safety net they provide. By watching the watchmen, we can make sure our tests really protect us, and we aren’t just green-washing our IDEs to a false sense of security.
Talk from SciFiDevCon 2025
https://www.scifidevcon.com/courses/2025-scifidevcon/contents/680efa43ae4f5
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...Andre Hora
Unittest and pytest are the most popular testing frameworks in Python. Overall, pytest provides some advantages, including simpler assertion, reuse of fixtures, and interoperability. Due to such benefits, multiple projects in the Python ecosystem have migrated from unittest to pytest. To facilitate the migration, pytest can also run unittest tests, thus, the migration can happen gradually over time. However, the migration can be timeconsuming and take a long time to conclude. In this context, projects would benefit from automated solutions to support the migration process. In this paper, we propose TestMigrationsInPy, a dataset of test migrations from unittest to pytest. TestMigrationsInPy contains 923 real-world migrations performed by developers. Future research proposing novel solutions to migrate frameworks in Python can rely on TestMigrationsInPy as a ground truth. Moreover, as TestMigrationsInPy includes information about the migration type (e.g., changes in assertions or fixtures), our dataset enables novel solutions to be verified effectively, for instance, from simpler assertion migrations to more complex fixture migrations. TestMigrationsInPy is publicly available at: https://github.com/altinoalvesjunior/TestMigrationsInPy.
Download YouTube By Click 2025 Free Full Activatedsaniamalik72555
Copy & Past Link 👉👉
https://dr-up-community.info/
"YouTube by Click" likely refers to the ByClick Downloader software, a video downloading and conversion tool, specifically designed to download content from YouTube and other video platforms. It allows users to download YouTube videos for offline viewing and to convert them to different formats.
Exploring Wayland: A Modern Display Server for the FutureICS
Wayland is revolutionizing the way we interact with graphical interfaces, offering a modern alternative to the X Window System. In this webinar, we’ll delve into the architecture and benefits of Wayland, including its streamlined design, enhanced performance, and improved security features.
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfTechSoup
In this webinar we will dive into the essentials of generative AI, address key AI concerns, and demonstrate how nonprofits can benefit from using Microsoft’s AI assistant, Copilot, to achieve their goals.
This event series to help nonprofits obtain Copilot skills is made possible by generous support from Microsoft.
What You’ll Learn in Part 2:
Explore real-world nonprofit use cases and success stories.
Participate in live demonstrations and a hands-on activity to see how you can use Microsoft 365 Copilot in your own work!
Join Ajay Sarpal and Miray Vu to learn about key Marketo Engage enhancements. Discover improved in-app Salesforce CRM connector statistics for easy monitoring of sync health and throughput. Explore new Salesforce CRM Synch Dashboards providing up-to-date insights into weekly activity usage, thresholds, and limits with drill-down capabilities. Learn about proactive notifications for both Salesforce CRM sync and product usage overages. Get an update on improved Salesforce CRM synch scale and reliability coming in Q2 2025.
Key Takeaways:
Improved Salesforce CRM User Experience: Learn how self-service visibility enhances satisfaction.
Utilize Salesforce CRM Synch Dashboards: Explore real-time weekly activity data.
Monitor Performance Against Limits: See threshold limits for each product level.
Get Usage Over-Limit Alerts: Receive notifications for exceeding thresholds.
Learn About Improved Salesforce CRM Scale: Understand upcoming cloud-based incremental sync.
DVDFab Crack FREE Download Latest Version 2025younisnoman75
⭕️➡️ FOR DOWNLOAD LINK : http://drfiles.net/ ⬅️⭕️
DVDFab is a multimedia software suite primarily focused on DVD and Blu-ray disc processing. It offers tools for copying, ripping, creating, and editing DVDs and Blu-rays, as well as features for downloading videos from streaming sites. It also provides solutions for playing locally stored video files and converting audio and video formats.
Here's a more detailed look at DVDFab's offerings:
DVD Copy:
DVDFab offers software for copying and cloning DVDs, including removing copy protections and creating backups.
DVD Ripping:
This allows users to rip DVDs to various video and audio formats for playback on different devices, while maintaining the original quality.
Blu-ray Copy:
DVDFab provides tools for copying and cloning Blu-ray discs, including removing Cinavia protection and creating lossless backups.
4K UHD Copy:
DVDFab is known for its 4K Ultra HD Blu-ray copy software, allowing users to copy these discs to regular BD-50/25 discs or save them as 1:1 lossless ISO files.
DVD Creator:
This tool allows users to create DVDs from various video and audio formats, with features like GPU acceleration for faster burning.
Video Editing:
DVDFab includes a video editing tool for tasks like cropping, trimming, adding watermarks, external subtitles, and adjusting brightness.
Video Player:
A free video player that supports a wide range of video and audio formats.
All-In-One:
DVDFab offers a bundled software package, DVDFab All-In-One, that includes various tools for handling DVD and Blu-ray processing.
Not So Common Memory Leaks in Java WebinarTier1 app
This SlideShare presentation is from our May webinar, “Not So Common Memory Leaks & How to Fix Them?”, where we explored lesser-known memory leak patterns in Java applications. Unlike typical leaks, subtle issues such as thread local misuse, inner class references, uncached collections, and misbehaving frameworks often go undetected and gradually degrade performance. This deck provides in-depth insights into identifying these hidden leaks using advanced heap analysis and profiling techniques, along with real-world case studies and practical solutions. Ideal for developers and performance engineers aiming to deepen their understanding of Java memory management and improve application stability.
2. • Provides the essential types, classes and functions for
everyday work with Kotlin.
• In version 1.3 it contains approximately 50 sub packages
organized in 4 categories:
Common, JVM, JS and Native.
Kotlin Std Lib
3. • Provides the essential types, classes and functions for
everyday work with Kotlin.
• In version 1.3 it contains approximately 50 sub packages
organized in 4 categories:
Common, JVM, JS and Native.
Kotlin Std Lib
6. • It’s an extension function.
• Caller is represented by it.
• Returns the block’s last line.
• It’s commonly used for nullability checking.
public inline fun <T, R> T.let(block: (T) -> R): R {
return block(this)
}
7. fun deleteTempPhoto() {
var tempImageFile: File? = // ...
tempImageFile?.let {
if (it.exists()) it.delete()
}
}
8. fun deleteTempPhoto() {
var tempImageFile: File? = // ...
if (tempImageFile != null) {
if (tempImageFile.exists()) // thanks smart cast!
tempImageFile.delete()
}
}
9. class SomeClass {
var tempImageFile: File? = null
fun deleteTempPhoto() {
if (tempImageFile != null && tempImageFile.exists())
tempImageFile.delete()
}
}
10. class SomeClass {
var tempImageFile: File? = null
fun deleteTempPhoto() {
if (tempImageFile != null && tempImageFile.exists())
tempImageFile.delete()
}
}
12. class SomeClass {
var tempImageFile: File? = null
fun deleteTempPhoto() {
if (tempImageFile != null && tempImageFile?.exists() == true )
tempImageFile?.delete()
}
}
😒😱
13. class SomeClass {
var tempImageFile: File? = null
fun deleteTempPhoto() {
tempImageFile?.let {
if (it.exists()) it.delete()
}
}
}
14. class SomeClass {
var tempImageFile: File? = null
fun deleteTempPhoto() {
tempImageFile?.let { file ->
if (file.exists()) file.delete()
}
}
}
😎
15. • It’s an extension function.
• Caller is represented by this.
• Returns the caller itself (this).
• It’s commonly used for initializing and configuring an
object.
public inline fun <T> T.apply(block: T.() -> Unit): T {
block()
return this
}
18. val chip = Chip(this).apply {
text = weatherType.name.capitalize()
setChipBackgroundColorResource(R.color.colorAccent)
isClickable = false
isCheckable = false
isCloseIconVisible = true
setOnCloseIconClickListener {
if (viewModel.unselectWeatherType(weatherType)) {
chipGroup.removeView(it)
}
}
}
chipGroup.addView(chip)
19. • It’s an extension function.
• Caller is represented by it.
• Returns the caller itself (this).
• It’s commonly used for chaining object initialization or
simple to separate one action from another.
public inline fun <T> T.also(block: (T) -> Unit): T {
block(this)
return this
}
20. val chip = Chip(this).apply {
text = weatherType.name.capitalize()
setChipBackgroundColorResource(R.color.colorAccent)
isClickable = false
isCheckable = false
isCloseIconVisible = true
setOnCloseIconClickListener {
if (viewModel.unselectWeatherType(weatherType)) {
chipGroup.removeView(it)
}
}
}
chipGroup.addView(chip)
22. • It’s an extension function.
• Caller is represented by this.
• Returns the block’s last line.
• It’s commonly used to get the result of an operation
using an object.
public inline fun <T, R> T.run(block: T.() -> R): R {
return block()
}
23. public inline fun <R> run(block: () -> R): R {
return block()
}
• It’s not an extension function.
• There’s no reference to the caller (once it’s not an
extension function).
• Returns the block’s last line.
• It’s commonly used to get the result of an operation.
24. private fun getFavoriteCity(): String {
val prefs =
PreferenceManager.getDefaultSharedPreferences(this)
return prefs.getString("favCity", null) ?:
getString(R.string.pref_city_default)
}
25. private fun getFavoriteCity() =
PreferenceManager.getDefaultSharedPreferences(this).run {
getString("favCity", null)
} ?: run {
getString(R.string.pref_city_default)
}
26. • It’s not an extension function.
• The caller is passed as parameter and is referenced by
this.
• Returns the block’s last line.
• It’s commonly used when you want to remember Delphi.
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
return receiver.block()
}
29. val webView: WebView? = loadWebView()
with(webView) {
settings.javaScriptEnabled = true
loadUrl("file:///android_asset/app_page.html")
}
Only safe (?.) or non-null asserted (!!.)
calls are allowed on a nullable receiver
of type WebView?
32. • T.let { } for nullability check.
• T.apply { } for object initialization.
• T.also { } for initialization chaining or a simple change of
scope.
• T.run { } to get a result from an object sequence of calls.
• run { } to get a result from a sequence of calls.
• with(T) { } for some reason you don’t know how to
explain… :)
Scope Functions - Summary
39. fun login(userName: String, password: String) {
// Do login
}
data class AuthUser(val name: String, val password: String)
fun login(authUser: AuthUser) {
// New login with user
}
40. fun login(userName: String, password: String) {
// Do login
}
@Experimental(Experimental.Level.WARNING)
annotation class NewApi
data class AuthUser(val name: String, val password: String)
fun login(authUser: AuthUser) {
// New login with user
}
41. fun login(userName: String, password: String) {
// Do login
}
@Experimental(Experimental.Level.WARNING)
annotation class NewApi
@NewApi
data class AuthUser(val name: String, val password: String)
@NewApi
fun login(authUser: AuthUser) {
// New login with user
}
42. fun login(userName: String, password: String) {
// Do login
}
@Experimental(Experimental.Level.WARNING)
annotation class NewApi
@NewApi
data class AuthUser(val name: String, val password: String)
@NewApi
fun login(authUser: AuthUser) {
// New login with user
}
@UseExperimental(NewApi::class)
fun main() {
login(AuthUser("ngvl", "123"))
}
66. try {
UserRepository.insertUser(new User("ngvl"));
} catch (NameTooShortException e) {
// handle name too short
}
object UserRepository {
@JvmStatic
@Throws(NameTooShortException::class)
fun insertUser(user: User) {
if (user.name.length < 5) {
throw NameTooShortException()
}
// insert user ...
}
}
67. data class Recipe(
var name: String? = null,
var ingredients: List<Ingredient> = mutableListOf()
)
data class Ingredient(
var description: String? = null,
var quantity: Int = 0,
var unity: String? = null
)
68. data class Recipe(
var name: String? = null,
var ingredients: List<Ingredient> = mutableListOf()
)
data class Ingredient(
var description: String? = null,
var quantity: Int = 0,
var unity: String? = null
)
fun recipe(build: Recipe.() -> Unit) = Recipe().apply(build)
fun Recipe.ingredient(build: Ingredient.() -> Unit) {
ingredients += Ingredient().apply(build)
}
public inline fun <T> T.apply(block: T.() -> Unit): T {
block()
return this
}
69. fun recipe(build: Recipe.() -> Unit) = Recipe().apply(build)
fun Recipe.ingredient(build: Ingredient.() -> Unit) {
ingredients += Ingredient().apply(build)
}
val recipe = recipe {
name = "Chocolate Cake"
ingredient {
name = "Flour"
quantity = 3
unity = "cups"
}
}
println(recipe)
Recipe(name=Flour, ingredients=[
Ingredient(description=null, quantity=3, unity=cups)]
) 🤔
70. data class Recipe(
var name: String? = null,
var ingredients: List<Ingredient> = mutableListOf()
)
data class Ingredient(
var description: String? = null,
var quantity: Int = 0,
var unity: String? = null
)
fun recipe(build: Recipe.() -> Unit) = Recipe().apply(build)
fun Recipe.ingredient(build: Ingredient.() -> Unit) {
ingredients += Ingredient().apply(build)
}
71. @DslMarker annotation class RecipeLang
@RecipeLang
data class Recipe(
var name: String? = null,
var ingredients: List<Ingredient> = mutableListOf()
)
@RecipeLang
data class Ingredient(
var description: String? = null,
var quantity: Int = 0,
var unity: String? = null
)
fun recipe(build: Recipe.() -> Unit) = Recipe().apply(build)
fun Recipe.ingredient(build: Ingredient.() -> Unit) {
ingredients += Ingredient().apply(build)
}
72. val recipe = recipe {
name = "Chocolate Cake"
ingredient {
name = "Flour"
quantity = 3
unity = "cups"
}
}
println(recipe)
fun recipe(build: Recipe.() -> Unit) = Recipe().apply(build)
fun Recipe.ingredient(build: Ingredient.() -> Unit) {
ingredients += Ingredient().apply(build)
}
Compile error: 'var name: String?'
can't be called in this context by
implicit receiver.
Use the explicit one if necessary
75. • @Deprecated and @Experimental help to document the
evolution of your code
• @Jvm* annotations help the integration with Java code.
• @DslMarker create scopes for your DSLs.
Annotations - Summary
77. abstract class Individual(
val name: String,
val surname: String,
val age: Int
)
class Student(
name: String,
surname: String,
age: Int,
val university: String
) : Individual(name, surname, age)
class Worker(
name: String,
surname: String,
age: Int,
val company: String
) : Individual(name, surname, age)
78. abstract class Individual(
val name: String,
val surname: String,
val age: Int
)
class Student(
name: String,
surname: String,
age: Int,
val university: String
) : Individual(name, surname, age)
class Worker(
name: String,
surname: String,
age: Int,
val company: String
) : Individual(name, surname, age)
79. interface Individual {
val name: String
val surname: String
val age: Int
}
data class IndividualData(
override val name: String,
override val surname: String,
override val age: Int
) : Individual
data class Student(
val data: IndividualData,
val university: String
) : Individual by data
data class Worker(
val data: IndividualData,
val company: String
) : Individual by data
80. interface Individual {
val name: String
val surname: String
val age: Int
}
data class IndividualData(
override val name: String,
override val surname: String,
override val age: Int
) : Individual
data class Student(
val data: IndividualData,
val university: String
) : Individual by data
data class Worker(
val data: IndividualData,
val company: String
) : Individual by data
val student = Student(
IndividualData("Nelson", "Leal", 36), "Universo"
)
student.run {
println("$name $surname - $age - $university")
}
Nelson Leal - 36 - Universo
81. class Repository {
private val peopleDAO: PeopleDAO by lazy {
Database.getPeopleDAO()
}
fun insert(person: Person) {
peopleDAO.add(person)
}
fun all(): List<Person> = peopleDAO.list()
}
82. class Repository {
private val peopleDAO: PeopleDAO by lazy {
Database.getPeopleDAO()
}
fun insert(person: Person) {
peopleDAO.add(person)
}
fun all(): List<Person> = peopleDAO.list()
}
83. class Repository {
private val peopleDAO: PeopleDAO by lazy {
Database.getPeopleDAO()
}
fun insert(person: Person) {
peopleDAO.add(person)
}
fun all(): List<Person> = peopleDAO.list()
}
val repo = Repository()
repo.insert(Person("1", "Nelson"))
repo.insert(Person("2", "Glauber"))
repo.all().forEach(::printPerson)
84. Delegates.vetoable(0) { // it's an inline function
kprop, oldValue, newValue ->
newValue in 0..122 // Jeanne Calmen
}
85. val ageDelegate = {
Delegates.vetoable(0) {
kprop, oldValue, newValue ->
newValue in 0..122
}
}
if you don't use it as a function, it will return
the last value for the new instance
86. val ageDelegate = {
Delegates.vetoable(0) {
kprop, oldValue, newValue ->
newValue in 0..122
}
}
class Person(val id: String, val name: String) {
var age: Int by ageDelegate()
}
87. val ageDelegate = {
Delegates.vetoable(0) {
kprop, oldValue, newValue ->
newValue in 0..122
}
}
class Person(val id: String, val name: String) {
var age: Int by ageDelegate()
}
val p = Person("3", "Nelson")
p.age = -1
printPerson(p)
p.age = 150
printPerson(p)
p.age = 35
printPerson(p)
3 - Nelson - 0
3 - Nelson - 0
3 - Nelson - 35
88. interface OnFilterCallback {
fun onFilterChanged(f: Filter)
}
class Filter {
var minBathNum: Int = 0
var minPrice: Float = 0f
private val callbacks = mutableSetOf<OnFilterCallback>()
fun addOnFilterChangedCallback(callback: OnFilterCallback) {
callbacks += callback
}
}
89. class Filter {
var minBathNum: Int = 0
var minPrice: Float = 0f
private val callbacks = mutableSetOf<OnFilterCallback>()
fun addOnFilterChangedCallback(callback: OnFilterCallback) {
callbacks += callback
}
fun notifyObservers() {
callbacks.forEach{ it.onFilterChanged(this) }
}
}
90. class FilterDelegate<T>(initial: T) {
var internal: T = initial
operator fun getValue(thisRef: Filter, prop: KProperty<*>): T {
return internal
}
operator fun setValue(thisRef: Filter, prop: KProperty<*>, value: T) {
internal = value
thisRef.notifyObservers()
}
}
91. interface OnFilterCallback {
fun onFilterChanged(f: Filter)
}
class Filter {
var minBathNum: Int by FilterDelegate(0)
var minPrice: Float by FilterDelegate(0f)
private val callbacks = mutableSetOf<OnFilterCallback>()
fun addOnFilterChangedCallback(callback: OnFilterCallback) {
callbacks += callback
}
fun notifyObservers() {
callbacks.forEach{ it.onFilterChanged(this) }
}
}
94. fun <T> Filter.filterDelegate(initialValue: T) =
Delegates.observable(initialValue) { prop, oldValue, newValue ->
println("old: $oldValue -> new: $newValue")
this.notifyObservers()
}
class Filter {
var minBathNum: Int by filterDelegate(0)
var minPrice: Float by filterDelegate(0f)
...
}
96. • Interface delegation for composition.
• lazy for… lazy initialization.
• vetoable to define a validation to be reused.
• observable if you need both old and new value.
• Custom delegates for everything else.
Delegates - Summary
97. • Std Lib has a lot of functions to help you to write a more
simple, readable and concise code.
• Check it out the lib internals. You’ll learn a lot!
• Check it out the Kotlin Koans (https://play.kotlinlang.org/
koans). It’s a good place to start (or recap)!
• Write Kotlin code, enjoy the std lib and have fun! 😉
Wrap up!
98. • Kotlin Standard Functions
https://medium.com/androiddevelopers/kotlin-standard-functions-
cheat-sheet-27f032dd4326
• Mastering Kotlin standard functions: run, with, let, also and apply
https://medium.com/@elye.project/mastering-kotlin-standard-
functions-run-with-let-also-and-apply-9cd334b0ef84
• Java Friendly Kotlin
https://codelabs.developers.google.com/codelabs/java-friendly-kotlin
• Simpler Kotlin class hierarchies using class delegation
https://proandroiddev.com/simpler-kotlin-class-hierarchies-using-
class-delegation-35464106fed5
References