The document provides idiomatic Kotlin coding style guidelines and best practices for expressions, classes, functions, and the standard library. Some key recommendations include using 'when' and 'try' as expression bodies, avoiding classes just for functions, extracting non-essential APIs to extensions, using data classes, type aliases, and destructuring declarations, and leveraging functions like 'apply', 'filterIsInstance', and 'groupBy' from the standard library. Overall the document advises organizing code in a concise and functional way that fully utilizes Kotlin language features.
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.
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesLauren Yew
Kotlin Coroutines is a powerful threading library for Kotlin, released by JetBrains in 2018. At The New York Times, we recently migrated our core libraries and parts of our News app from RxJava to Kotlin Coroutines. In this talk we’ll share lessons learned and best practices to understand, migrate to, and use Kotlin Coroutines & Flows.
In this presentation, you will learn:
What Coroutines are and how they function
How to use Kotlin Coroutines & Flows (with real world examples and demos)
Where and why you should use Coroutines & Flows in your app
How to avoid the pitfalls of Coroutines
Kotlin Coroutines vs. RxJava
Lessons learned from migrating to Kotlin Coroutines from RxJava in large legacy projects & libraries
By the end of this talk, you will be able to apply Kotlin Coroutines to your own app, run the provided sample code yourself, and convince your team to give Kotlin Coroutines a try!
As a part of kotlinx.coroutines 1.2 Flow was introduced as a cold asynchronous data stream. How does it work? What we can do with it? Is it that we waiting so long for replacing Rx? The talk has answers to them.
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.
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesLauren Yew
Kotlin Coroutines is a powerful threading library for Kotlin, released by JetBrains in 2018. At The New York Times, we recently migrated our core libraries and parts of our News app from RxJava to Kotlin Coroutines. In this talk we’ll share lessons learned and best practices to understand, migrate to, and use Kotlin Coroutines & Flows.
In this presentation, you will learn:
What Coroutines are and how they function
How to use Kotlin Coroutines & Flows (with real world examples and demos)
Where and why you should use Coroutines & Flows in your app
How to avoid the pitfalls of Coroutines
Kotlin Coroutines vs. RxJava
Lessons learned from migrating to Kotlin Coroutines from RxJava in large legacy projects & libraries
By the end of this talk, you will be able to apply Kotlin Coroutines to your own app, run the provided sample code yourself, and convince your team to give Kotlin Coroutines a try!
As a part of kotlinx.coroutines 1.2 Flow was introduced as a cold asynchronous data stream. How does it work? What we can do with it? Is it that we waiting so long for replacing Rx? The talk has answers to them.
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Learn about how to define and invoke methods in Java, how to use parameters and return results. Watch the video lesson here:
https://softuni.org/code-lessons/java-foundations-certification-methods
Composition is a fundamental principle of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with a simple FizzBuzz example, and ending with a complete (object-free!) web application.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
Utilizing Kotlin Flows in an Android application
Vijay will be revealing to you the kind of challenges we face while working with asynchronous data streams and how Kotlin Flows solves them.
Learn the latest tips, tricks, and tools for Android Development from our international team of Android Developers in Bangkok!
A step towards the way you write the code in React application.In this presentation, I have given introduction about React hooks. Why we need it in our react applications and describe about the two most commonly used React Hooks API useState and useEffect. I also given the links of code snippets I added in these slides
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшeQAFest
Page Objects, вероятно, самый известный на сегодня паттерн, используемый в автоматизации через UI. И самый простой, скажете вы? Не соглашусь, по моим наблюдением применение данного паттерна таит в себе подводные камни даже для наиболее типичных веб-приложений.
В данном докладе я познакомлю вас с тремя простыми и практичными видами PageObject архитектуры - Static, Void и Fluent, продемонстрирую использование кодом, сравню плюсы и минусы подходов. Также я расскажу о важных недостатках Yandex HTMLElements и о некоторых других неудачных подходах, которые повторяются из одного самодельного фреймворка в другой. Вы увидите на примерах, как простой код решает проблемы лучше, чем слишком умный. Примеры на языке Java/Selenide легко переносимы и на другие языки программирования (.NET, Python и другие).
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Learn about how to define and invoke methods in Java, how to use parameters and return results. Watch the video lesson here:
https://softuni.org/code-lessons/java-foundations-certification-methods
Composition is a fundamental principle of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with a simple FizzBuzz example, and ending with a complete (object-free!) web application.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
Utilizing Kotlin Flows in an Android application
Vijay will be revealing to you the kind of challenges we face while working with asynchronous data streams and how Kotlin Flows solves them.
Learn the latest tips, tricks, and tools for Android Development from our international team of Android Developers in Bangkok!
A step towards the way you write the code in React application.In this presentation, I have given introduction about React hooks. Why we need it in our react applications and describe about the two most commonly used React Hooks API useState and useEffect. I also given the links of code snippets I added in these slides
QA Fes 2016. Алексей Виноградов. Page Objects: лучше проще, да лучшeQAFest
Page Objects, вероятно, самый известный на сегодня паттерн, используемый в автоматизации через UI. И самый простой, скажете вы? Не соглашусь, по моим наблюдением применение данного паттерна таит в себе подводные камни даже для наиболее типичных веб-приложений.
В данном докладе я познакомлю вас с тремя простыми и практичными видами PageObject архитектуры - Static, Void и Fluent, продемонстрирую использование кодом, сравню плюсы и минусы подходов. Также я расскажу о важных недостатках Yandex HTMLElements и о некоторых других неудачных подходах, которые повторяются из одного самодельного фреймворка в другой. Вы увидите на примерах, как простой код решает проблемы лучше, чем слишком умный. Примеры на языке Java/Selenide легко переносимы и на другие языки программирования (.NET, Python и другие).
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
Помните легендарные Java Puzzlers? Да-да, те самые, с Джошом Блохом и Нилом Гафтером? Ну, по которым ещё книжку написали? Так вот, в Groovy всё ещё веселее.
В смысле — задачки ещё более странные, и ответы ещё более поразительные. Этот доклад для вас, Groovy-разработчики, мы покажем вам настоящие, большие и красивые подводные камни! И для вас, Java-разработчики, потому что таких вещей на Java-подобном синтакисе вы точно никогда не видели! И для вас, PHP-разработчики… хотя, нет, не для вас :)
Всем точно будет весело — ваши ведущие Женя и Барух будут зажигать, шутить, спорить, бросаться футболками в публику, и самое главное — заставят вас офигевать от Groovy.
How to Build Developer Tools on Top of IntelliJ Platformintelliyole
Slides from a July 30th webinar on building tools for IntelliJ Platform:
* What is IntelliJ Platform?
* Who is it suited for?
* Why is it better than Eclipse and Netbeans platforms?
* How is it different from IntelliJ IDEA Community Edition?
* Is it possible to build a commercial product based on IntelliJ Platform?
* Plugins for IntelliJ IDEA Community Edition vs products based on IntelliJ Platform.
* What steps must be taken to create a product based on IntelliJ Platform?
* How you can contribute to IntelliJ Platform?
Launch Your Streaming Platforms in MinutesRoshan Dwivedi
The claim of launching a streaming platform in minutes might be a bit of an exaggeration, but there are services that can significantly streamline the process. Here's a breakdown:
Pros of Speedy Streaming Platform Launch Services:
No coding required: These services often use drag-and-drop interfaces or pre-built templates, eliminating the need for programming knowledge.
Faster setup: Compared to building from scratch, these platforms can get you up and running much quicker.
All-in-one solutions: Many services offer features like content management systems (CMS), video players, and monetization tools, reducing the need for multiple integrations.
Things to Consider:
Limited customization: These platforms may offer less flexibility in design and functionality compared to custom-built solutions.
Scalability: As your audience grows, you might need to upgrade to a more robust platform or encounter limitations with the "quick launch" option.
Features: Carefully evaluate which features are included and if they meet your specific needs (e.g., live streaming, subscription options).
Examples of Services for Launching Streaming Platforms:
Muvi [muvi com]
Uscreen [usencreen tv]
Alternatives to Consider:
Existing Streaming platforms: Platforms like YouTube or Twitch might be suitable for basic streaming needs, though monetization options might be limited.
Custom Development: While more time-consuming, custom development offers the most control and flexibility for your platform.
Overall, launching a streaming platform in minutes might not be entirely realistic, but these services can significantly speed up the process compared to building from scratch. Carefully consider your needs and budget when choosing the best option for you.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaYara Milbes
Discover the transformative power of the WhatsApp API in our latest SlideShare presentation, "Top 7 Unique WhatsApp API Benefits." In today's fast-paced digital era, effective communication is crucial for both personal and professional success. Whether you're a small business looking to enhance customer interactions or an individual seeking seamless communication with loved ones, the WhatsApp API offers robust capabilities that can significantly elevate your experience.
In this presentation, we delve into the top 7 distinctive benefits of the WhatsApp API, provided by the leading WhatsApp API service provider in Saudi Arabia. Learn how to streamline customer support, automate notifications, leverage rich media messaging, run scalable marketing campaigns, integrate secure payments, synchronize with CRM systems, and ensure enhanced security and privacy.
3. Use ‘when’ as expression body
fun parseNum(number: String): Int? {
when (number) {
"one" -> return 1
"two" -> return 2
else -> return null
}
}
4. Use ‘when’ as expression body
fun parseNum(number: String): Int? {
when (number) {
"one" -> return 1
"two" -> return 2
else -> return null
}
}
fun parseNum(number: String) =
when (number) {
"one" -> 1
"two" -> 2
else -> null
}
5. Use ‘try’ as expression body
fun tryParse(number: String): Int? {
try {
return Integer.parseInt(number)
}
catch (e: NumberFormatException) {
return null
}
}
6. Use ‘try’ as expression body
fun tryParse(number: String): Int? {
try {
return Integer.parseInt(number)
}
catch (e: NumberFormatException) {
return null
}
}
fun tryParse(number: String) =
try {
Integer.parseInt(number)
}
catch (e: NumberFormatException) {
null
}
7. Use ‘try’ as expression
fun tryParse(number: String): Int? {
try {
return Integer.parseInt(number)
}
catch (e: NumberFormatException) {
return null
}
}
fun tryParse(number: String): Int? {
val n = try {
Integer.parseInt(number)
} catch (e: NumberFormatException) {
null
}
println(n)
return n
}
8. Use elvis with ‘return’ and ‘throw’
fun processPerson(person: Person) {
val name = person.name
if (name == null)
throw IllegalArgumentException(
"Named required")
val age = person.age
if (age == null) return
println("$name: $age")
}
class Person(val name: String?,
val age: Int?)
9. Use elvis with ‘return’ and ‘throw’
fun processPerson(person: Person) {
val name = person.name
if (name == null)
throw IllegalArgumentException(
"Named required")
val age = person.age
if (age == null) return
println("$name: $age")
}
fun processPerson(person: Person) {
val name = person.name ?:
throw IllegalArgumentException(
"Name required")
val age = person.age ?: return
println("$name: $age")
}
class Person(val name: String?,
val age: Int?)
10. Use range checks instead of comparison pairs
fun isLatinUppercase(c: Char) =
c >= 'A' && c <= 'Z'
11. Use range checks instead of comparison pairs
fun isLatinUppercase(c: Char) =
c >= 'A' && c <= 'Z'
fun isLatinUppercase(c: Char) =
c in 'A'..'Z'
13. Don’t create classes just to put functions in
class StringUtils {
companion object {
fun isPhoneNumber(s: String) =
s.length == 7 &&
s.all { it.isDigit() }
}
}
14. Don’t create classes just to put functions in
class StringUtils {
companion object {
fun isPhoneNumber(s: String) =
s.length == 7 &&
s.all { it.isDigit() }
}
}
object StringUtils {
fun isPhoneNumber(s: String) =
s.length == 7 &&
s.all { it.isDigit() }
}
15. Don’t create classes just to put functions in
class StringUtils {
companion object {
fun isPhoneNumber(s: String) =
s.length == 7 &&
s.all { it.isDigit() }
}
} fun isPhoneNumber(s: String) =
s.length == 7 &&
s.all { it.isDigit() }
object StringUtils {
fun isPhoneNumber(s: String) =
s.length == 7 &&
s.all { it.isDigit() }
}
16. Use extension functions copiously
fun isPhoneNumber(s: String) =
s.length == 7 &&
s.all { it.isDigit() }
17. Use extension functions copiously
fun isPhoneNumber(s: String) =
s.length == 7 &&
s.all { it.isDigit() }
fun String.isPhoneNumber() =
length == 7 &&
all { it.isDigit() }
18. Avoid using member extension functions
(unless required for DSLs)
class PhoneBook {
fun String.isPhoneNumber() =
length == 7 &&
all { it.isDigit() }
}
19. Avoid using member extension functions
(unless required for DSLs)
class PhoneBook {
fun String.isPhoneNumber() =
length == 7 &&
all { it.isDigit() }
}
class PhoneBook {
}
private fun
String.isPhoneNumber() =
length == 7 &&
all { it.isDigit() }
20. Don't use member extensions with
containing class as the receiver
class PhoneBook {
fun PhoneBook.find(name: String)=
"1234567"
}
21. Don't use member extensions with
containing class as the receiver
class PhoneBook {
fun PhoneBook.find(name: String)=
"1234567"
}
class PhoneBook {
fun find(name: String) =
"1234567"
}
22. Consider extracting non-essential API
of classes into extensions
class Person(val firstName: String,
val lastName: String) {
val fullName: String
get() = "$firstName $lastName"
}
23. Consider extracting non-essential API
of classes into extensions
class Person(val firstName: String,
val lastName: String) {
val fullName: String
get() = "$firstName $lastName"
}
class Person(val firstName: String,
val lastName: String)
val Person.fullName: String
get() = "$firstName $lastName"
24. Use default parameter values instead of overloads
wherever possible
class Phonebook {
fun print() {
print(",")
}
fun print(separator: String) {
}
}
fun main(args: Array<String>) {
Phonebook().print("|")
}
25. Use default parameter values instead of overloads
wherever possible
class Phonebook {
fun print() {
print(",")
}
fun print(separator: String) {
}
}
fun main(args: Array<String>) {
Phonebook().print("|")
}
class Phonebook {
fun print(
separator: String = ",") {
}
}
fun main(args: Array<String>) {
Phonebook().print(
separator = "|")
}
26. Use ‘lateinit’ for properties that can’t be initialised
in a constructor
class MyTest {
class State(val data: String)
var state: State? = null
@Before fun setup() {
state = State("abc")
}
@Test fun foo() {
Assert.assertEquals(
"abc", state!!.data)
}
}
27. Use ‘lateinit’ for properties that can’t be initialised
in a constructor
class MyTest {
class State(val data: String)
var state: State? = null
@Before fun setup() {
state = State("abc")
}
@Test fun foo() {
Assert.assertEquals(
"abc", state!!.data)
}
}
class MyTest {
class State(val data: String)
lateinit var state: State
@Before fun setup() {
state = State("abc")
}
@Test fun foo() {
Assert.assertEquals(
"abc", state.data)
}
}
28. Use type aliases for functional types and
collections
class EventDispatcher {
fun addClickHandler(
handler: (Event) -> Unit) {
}
fun removeClickHandler(
handler: (Event) -> Unit) {
}
}
29. Use type aliases for functional types and
collections
class EventDispatcher {
fun addClickHandler(
handler: (Event) -> Unit) {
}
fun removeClickHandler(
handler: (Event) -> Unit) {
}
}
typealias ClickHandler =
(Event) -> Unit
class EventDispatcher {
fun addClickHandler(
handler: ClickHandler) {
}
fun removeClickHandler(
handler: ClickHandler) {
}
}
30. Use type aliases for functional types and
collections
class EventDispatcher {
fun addClickHandler(
handler: (Event) -> Unit) {
}
fun removeClickHandler(
handler: (Event) -> Unit) {
}
}
typealias ClickHandler =
(Event) -> Unit
typealias HandlerMap =
Map<EventType, List<Event>>
31. Use data classes to return multiple values
fun namedNum(): Pair<Int, String> =
1 to "one"
fun main(args: Array<String>) {
val pair = namedNum()
val number = pair.first
val name = pair.second
}
32. Use data classes to return multiple values
fun namedNum(): Pair<Int, String> =
1 to "one"
fun main(args: Array<String>) {
val pair = namedNum()
val number = pair.first
val name = pair.second
}
data class NamedNumber(
val number: Int,
val name: String)
fun namedNum() =
NamedNumber(1, "one")
fun main(args: Array<String>) {
val (number, name) =
namedNum()
}
33. Use destructuring in loops
fun printMap(m: Map<String, String>) {
for (e in m.entries) {
println("${e.key} -> ${e.value}")
}
}
34. Use destructuring in loops
fun printMap(m: Map<String, String>) {
for (e in m.entries) {
println("${e.key} -> ${e.value}")
}
}
fun printMap(m: Map<String, String>) {
for ((key, value) in m) {
println("$key -> $value")
}
}
35. Use destructuring with lists
fun splitNameExt(fn: String): NameExt {
if ('.' in fn) {
val parts = fn.split('.', limit = 2)
return NameExt(parts[0], parts[1])
}
return NameExt(fn, null)
}
data class NameExt(val name: String,
val ext: String?)
36. Use destructuring with lists
fun splitNameExt(fn: String): NameExt {
if ('.' in fn) {
val parts = fn.split('.', limit = 2)
return NameExt(parts[0], parts[1])
}
return NameExt(fn, null)
}
fun splitNameExt(fn: String): NameExt {
if ('.' in fn) {
val (name, ext) =
fn.split('.', limit = 2)
return NameExt(name, ext)
}
return NameExt(fn, null)
}
data class NameExt(val name: String,
val ext: String?)
37. Use ‘copy’ method for data classes
class Person(val name: String,
var age: Int)
fun happyBirthday(person: Person) {
person.age++
}
38. Use ‘copy’ method for data classes
class Person(val name: String,
var age: Int)
fun happyBirthday(person: Person) {
person.age++
}
data class Person(val name: String,
val age: Int)
fun happyBirthday(person: Person) =
person.copy(
age = person.age + 1)
40. Use ‘coerceIn’ to ensure a number is in range
fun updateProgress(value: Int) {
val newValue = when {
value < 0 -> 0
value > 100 -> 100
else -> value
}
}
41. Use ‘coerceIn’ to ensure a number is in range
fun updateProgress(value: Int) {
val newValue = when {
value < 0 -> 0
value > 100 -> 100
else -> value
}
}
fun updateProgress(value: Int) {
val newValue =
value.coerceIn(0, 100)
}
42. Use ‘apply’ for object initialisation
fun createLabel(): JLabel {
val label = JLabel("Foo")
label.foreground = Color.RED
label.background = Color.BLUE
return label
}
43. Use ‘apply’ for object initialisation
fun createLabel(): JLabel {
val label = JLabel("Foo")
label.foreground = Color.RED
label.background = Color.BLUE
return label
}
fun createLabel() =
JLabel("Foo").apply {
foreground = Color.RED
background = Color.BLUE
}
44. Use ‘filterIsInstance’ to filter a list by object type
fun findStrings(objs: List<Any>) =
objs.filter { it is String }
45. Use ‘filterIsInstance’ to filter a list by object type
fun findStrings(objs: List<Any>) =
objs.filter { it is String }
fun findStrings(objs: List<Any>) =
obs.filterIsInstance<String>()
46. Use ‘mapNotNull’ to apply a function and select
items for which it returns a non-null value
fun listErrors(
results: List<Result>) =
results
.map { it.error }
.filterNotNull()
data class Result(val data: Any?,
val error: String?)
47. Use ‘mapNotNull’ to apply a function and select
items for which it returns a non-null value
fun listErrors(
results: List<Result>) =
results
.map { it.error }
.filterNotNull()
fun listErrors(
results: List<Result>) =
results.mapNotNull {
it.error
}
data class Result(val data: Any?,
val error: String?)
48. Use ‘compareBy’ for multi-step comparisons
fun sortPersons(persons: List<Person>) =
persons.sortedWith(
Comparator<Person> { p1, p2 ->
val rc =
p1.name.compareTo(p2.name)
if (rc != 0)
rc
else
p1.age - p2.age
})
class Person(val name: String,
val age: Int)
49. Use ‘compareBy’ for multi-step comparisons
fun sortPersons(persons: List<Person>) =
persons.sortedWith(
Comparator<Person> { p1, p2 ->
val rc =
p1.name.compareTo(p2.name)
if (rc != 0)
rc
else
p1.age - p2.age
})
fun sortPersons(persons: List<Person>) =
persons.sortedWith(
compareBy(Person::name,
Person::age))
class Person(val name: String,
val age: Int)
50. Use ‘groupBy’ to group items in a collection
fun analyzeLog(log: List<Request>) {
val map = mutableMapOf<String,
MutableList<Request>>()
for (request in log) {
map.getOrPut(request.url)
{ mutableListOf() }
.add(request)
}
}
class Request(val url: String,
val remoteIP: String,
val timestamp: Long)
51. Use ‘groupBy’ to group items in a collection
fun analyzeLog(log: List<Request>) {
val map = mutableMapOf<String,
MutableList<Request>>()
for (request in log) {
map.getOrPut(request.url)
{ mutableListOf() }
.add(request)
}
}
fun analyzeLog(log: List<Request>) {
val map = log.groupBy(Request::url)
}
class Request(val url: String,
val remoteIP: String,
val timestamp: Long)
52. Use String methods for string parsing
val pattern = Regex("(.+)/([^/]*)")
fun splitPath(path: String): PathParts {
val match = pattern.matchEntire(path)
?: return PathParts("", path)
return PathParts(match.groupValues[1],
match.groupValues[2])
}
data class PathParts(val dir: String,
val name: String)
53. Use String methods for string parsing
val pattern = Regex("(.+)/([^/]*)")
fun splitPath(path: String): PathParts {
val match = pattern.matchEntire(path)
?: return PathParts("", path)
return PathParts(match.groupValues[1],
match.groupValues[2])
}
fun splitPath(path: String) =
PathParts(
path.substringBeforeLast('/', ""),
path.substringAfterLast(‘/'))
data class PathParts(val dir: String,
val name: String)