These are the slides of the presentation I gave at the JetBrains HQ by the RAI in Amsterdam named "Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin". I want to express a big thank you to Xebia and JetBrains for the opportunity. I gave this presentation on the 24th of April 2024.
The document discusses parallel programming in .NET. It covers two main strategies for parallelism - data parallelism and task parallelism. For data parallelism, it describes using Parallel.For to partition work over collections. For task parallelism, it discusses using the Task Parallel Library to create and run independent tasks concurrently, allowing work to be distributed across multiple processors. It provides examples of creating tasks implicitly with Parallel.Invoke and explicitly by instantiating Task objects and passing delegates.
The document describes a C program that implements various operations on arrays, strings, and stacks. It includes functions to create, display, insert, and delete elements from an array. For strings, it includes functions to read main, pattern, and replace strings, find occurrences of a pattern, and replace the pattern with the given string. For stacks, it includes functions to push and pop elements, check if a number is a palindrome, and display stack elements. The program uses menus to select these different operations and test cases are provided to demonstrate the output.
This document discusses concurrent programming and multithreaded programming in Java. It covers key topics such as creating and controlling threads, thread safety and synchronization, and using bounded queues to allow cooperation between producer and consumer threads.
The document summarizes new features in C# 4.0 including optional and named parameters, dynamic typing, tuples, complex numbers, parallel programming, and thread-safe data structures. It also mentions code contracts, memory-mapped files, and the Managed Extensibility Framework.
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.
The document summarizes Software Transactional Memory (STM) and the Multiverse framework. STM provides an alternative to classic locking-based concurrency control using transactions on memory. Multiverse is an STM framework for Java that uses transactions to provide atomic, isolated and consistent access to shared memory without exposing locking details. It supports various programming models including POJO and managed reference based approaches.
We have this new language, Swift, which takes some familiar Apple patterns, and introduces some new ones. With tools like closures and method chaining, there are definitely some new ways to solve the age-old Obj-c architecture challenges. This talk will walk through some of the most common Obj-c design patterns rewritten in Swift, and showcase the strengths and weaknesses of this new language.
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
Erlang excels at building distributed, fault-tolerant, concurrent applications due to its lightweight process model and built-in support for distribution. However, Java is more full-featured and is generally a better choice for applications that require more traditional object-oriented capabilities or need to interface with existing Java libraries and frameworks. Both languages have their appropriate uses depending on the requirements of the specific application being developed.
The document discusses parallel programming in .NET. It covers two main strategies for parallelism - data parallelism and task parallelism. For data parallelism, it describes using Parallel.For to partition work over collections. For task parallelism, it discusses using the Task Parallel Library to create and run independent tasks concurrently, allowing work to be distributed across multiple processors. It provides examples of creating tasks implicitly with Parallel.Invoke and explicitly by instantiating Task objects and passing delegates.
The document describes a C program that implements various operations on arrays, strings, and stacks. It includes functions to create, display, insert, and delete elements from an array. For strings, it includes functions to read main, pattern, and replace strings, find occurrences of a pattern, and replace the pattern with the given string. For stacks, it includes functions to push and pop elements, check if a number is a palindrome, and display stack elements. The program uses menus to select these different operations and test cases are provided to demonstrate the output.
This document discusses concurrent programming and multithreaded programming in Java. It covers key topics such as creating and controlling threads, thread safety and synchronization, and using bounded queues to allow cooperation between producer and consumer threads.
The document summarizes new features in C# 4.0 including optional and named parameters, dynamic typing, tuples, complex numbers, parallel programming, and thread-safe data structures. It also mentions code contracts, memory-mapped files, and the Managed Extensibility Framework.
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.
The document summarizes Software Transactional Memory (STM) and the Multiverse framework. STM provides an alternative to classic locking-based concurrency control using transactions on memory. Multiverse is an STM framework for Java that uses transactions to provide atomic, isolated and consistent access to shared memory without exposing locking details. It supports various programming models including POJO and managed reference based approaches.
We have this new language, Swift, which takes some familiar Apple patterns, and introduces some new ones. With tools like closures and method chaining, there are definitely some new ways to solve the age-old Obj-c architecture challenges. This talk will walk through some of the most common Obj-c design patterns rewritten in Swift, and showcase the strengths and weaknesses of this new language.
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
Erlang excels at building distributed, fault-tolerant, concurrent applications due to its lightweight process model and built-in support for distribution. However, Java is more full-featured and is generally a better choice for applications that require more traditional object-oriented capabilities or need to interface with existing Java libraries and frameworks. Both languages have their appropriate uses depending on the requirements of the specific application being developed.
This document provides information about basic input and output in Java using System.out, System.in, and the Scanner class. It discusses using print and println to display output, and how to handle input using System.in, BufferedReader, and the Scanner class. The Scanner class allows more flexible input, including the ability to test the next input, read different data types, and handle input errors.
This document provides an introduction to the Kotlin programming language through a workshop series. It discusses key Kotlin concepts like statically typed vs dynamically typed languages, features of Kotlin like being interoperable with Java, and how to write basic Kotlin code like functions, variables, types, loops, and classes. The document includes code snippets and explanations to demonstrate Kotlin syntax and best practices.
The document discusses C++ interview questions and answers related to classes, inheritance, pointers, references, and operator overloading. It provides code examples to demonstrate concepts like passing objects by value vs reference, virtual functions, and inheritance. The examples are tested on Turbo C++, Microsoft VC++ compilers under Windows environment on x86 systems.
The document summarizes several Java 5 features including generics, enhanced for loops, autoboxing/unboxing, typesafe enums, varargs, static imports, and annotations. It provides examples and explanations of each feature.
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxbradburgess22840
In Class Assignmetz/CST280W13a-1.pdf
CST 280 In-Class Practice – Week 13
Manually determine the configuration of the priority queue (stored as a heap) created
by the following operations. Trace the following logic and define the output:
enqueue(7);
enqueue(17);
enqueue(2);
enqueue(5);
enqueue(22);
enqueue(19);
enqueue(6);
enqueue(11);
enqueue(13);
write the queue contents
dequeue and write front item
enqueue(15);
enqueue(8);
dequeue and write front item
dequeue and write front item
enqueue(24);
enqueue(14);
write the queue contents
Part 2
Then, verify the output by implementing the algorithm by rewriting the priority
queue demonstration program discussed in class. Files needed:
testPQueue.cpp pqType.h heap.cpp
Deliverables
• This cover sheet (with your names on it)
• Driver source code and output for verification program exectution.
In Class Assignmetz/CST280W13b.pdf
CST 280 In-Class Practice – Week 13
Use this page as a worksheet to sketch the progression of the elements up to the first
split for the QuickSort algorithm. Use the middle array element as the split value:
15 34 99 42 11 41 66 23 55 93 48
Next, access the file quickSort.cpp from the course web page. Tailor the program
by entering the array values above in place of the integer values used for an in-class
demonstration. Be sure to adjust the index range to match the size of this array.
Remember that the parameters to the QuickSort algorithm are starting and ending index
values, not the size of the array.
Next, insert code to demonstrate the state of the array after the first split. This should
verify what you did by hand above. Insert the following code at various points within
the partition function to “see” the array at various stages of processing:
for (int i = start; i <= end; i++) // <== ADD
cout << set[i] << ' ';
cout << endl;
Insert the code at these positions:
int partition(int set[], int start, int end)
{
int pivotValue, pivotIndex, mid;
mid = (start + end) / 2;
swap(set[start], set[mid]);
pivotIndex = start;
pivotValue = set[start];
ç HERE
for (int scan = start + 1; scan <= end; scan++)
{
if (set[scan] < pivotValue)
{
pivotIndex++;
swap(set[pivotIndex], set[scan]);
}
ç HERE
}
swap(set[start], set[pivotIndex]);
ç HERE
return pivotIndex;
}
Finally, identify the line that matches what you concluded above.
Deliverables:
Deliver the following for this assignment:
• This work sheet with a sketch of the array first split
• Program source code with required change
• Program output demonstrating array configuration after first split .
01 Introduction to Kotlin - Programming in Kotlin.pptxIvanZawPhyo
Kotlin is a programming language that is expressive, concise, and portable. It runs on the Java Virtual Machine and is fully interoperable with Java. Kotlin focuses on safety, interoperability, and tooling support. The basics of Kotlin include top-level functions, variables, if/when expressions, loops, ranges, null safety features, and string templates. Kotlin avoids null pointer exceptions through language features like the Elvis operator, safe calls, and non-null types.
Kotlin is a programming language that is expressive, concise, and portable. It runs on the Java Virtual Machine and is fully interoperable with Java. Kotlin focuses on safety, interoperability, and tooling support. The basics of Kotlin include top-level functions, variables, if/when expressions, loops, ranges, null safety features, and string templates. Kotlin avoids null pointer exceptions through language features like the Elvis operator, safe calls, and non-null types.
PQTimer.java A simple driver program to run timing t.docxjoyjonna282
/* PQTimer.java
A simple driver program to run timing tests on your ArrayPQ
and BinaryHeapPQ.
Programming Assignment #2
*/
import java.util.Iterator;
import java.util.ConcurrentModificationException;
import data_structures.*;
public class PQTimer {
public static void main(String [] args) {
///////////////////////////////////////////////////////////
/// Change this variable to something smaller if timing takes too long.
final int INITIAL_SIZE = 15000;
///////////////////////////////////////////////////////////
final int ITERATIONS = 10000;
final int NUMBER_OF_STEPS = 15;
final int MAX_SIZE = INITIAL_SIZE * NUMBER_OF_STEPS +1;
final int NUMBER_OF_PRIORITIES = 20;
int size = INITIAL_SIZE;
long sequence_number = 0;
long start, stop;
int priority;
PQTestObject [] array = new PQTestObject[MAX_SIZE];
for(int i=0; i < MAX_SIZE; i++)
array[i] = new PQTestObject((int) ((10000*Math.random() %
NUMBER_OF_PRIORITIES) +1), sequence_number++);
for(int j=0; j < 15; j++) {
PriorityQueue<PQTestObject> queue =
new HeapPriorityQueue<PQTestObject>(MAX_SIZE);
queue.clear();
for(int i = 0; i < size; i++)
queue.insert(array[i]);
start = System.currentTimeMillis(); // start the timer
for(int i = 0; i < ITERATIONS; i++) {
queue.insert(array[(int)(100000*Math.random() %
MAX_SIZE)]);
queue.remove();
}
stop = System.currentTimeMillis();
System.out.println("HeapPQ, Time for n=" + size + ": " +
(stop-start));
queue.clear();
queue = new ArrayPriorityQueue<PQTestObject>(MAX_SIZE);
for(int i = 0; i < size; i++)
queue.insert(array[i]);
start = System.currentTimeMillis(); // start the timer
for(int i = 0; i < ITERATIONS; i++) {
queue.insert(array[(int)(100000*Math.random() %
MAX_SIZE)]);
queue.remove();
}
stop = System.currentTimeMillis();
System.out.println("ArrayPQ, Time for n=" + size + ": " +
(stop-start)+"\n");
size += INITIAL_SIZE;
}
}
}
/* PQTestObject.java
A simple testing object that has a priority. The sequence
number in this class is NOT the insertion sequence number
you will have in the BinaryHeapPQ class. It is only used
for verification of correct behavior, and never used in
ordering objects of this class.
*/
public class PQTestObject implements Comparable<PQTestObject> {
private int priority;
private long sequence_number;
public PQTestObject(int p, long s) {
priority = p;
sequence_number = s;
}
public int compareTo(PQTestObject o) {
return priority - o.priority;
}
public String toString() {
...
The program defines a jagged array with 3 inner arrays of unspecified length. It initializes the inner arrays. It then iterates through the jagged array and sums all elements of the inner arrays. The total sum is returned.
1. The document discusses good and bad practices for writing unit tests. It emphasizes that tests should verify the expected behavior, fail clearly when something goes wrong, and use mocks and isolation to focus on the code being tested.
2. Some examples of bad tests shown include tests that don't make assertions or assertions that don't provide useful information on failure. Real objects are also used instead of mocks, obscuring the test.
3. Good practices include using mocks to isolate the code being tested, making sure tests fail clearly when something goes wrong, and focusing tests on expected behavior through clear assertions. Automated testing, fixing broken tests, and mastering testing tools are also emphasized.
Here are some suggestions to improve the test method name:
- shouldReturnNullWhenQueryReturnsNull
- shouldPassNullFromDaoWhenQueryReturnsNull
Using "should" makes the intent clearer - we expect the method to return null under certain conditions. Describing those conditions ("when query returns null") in the name provides more context than a generic "testQuery".
Overall, test method names should clearly communicate what is being tested and under what conditions we expect the test to pass or fail. This helps readers understand the purpose and focus of each test.
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.
The document describes a problem statement to create a simple calculation module that can process arithmetic expressions. It provides the input specification using Backus-Naur Form to define the syntax. It then describes taking a simple approach to solve this without using .NET Expression Trees, including possible test failures. It includes the code for a CalcEngine class to calculate expressions and CalcEngineTest class with unit tests to validate the calculations and failures.
Kotlin is a modern programming language that focuses on clarity, code safety and conciseness. Google officially adopted Kotlin by adding support into Android Studio in 2017 and since then has announced it as the preferred language for Android developers. Android app teams have incrementally added Kotlin code to their projects or have elected to start new Android projects in Kotlin moving forward. Having the app code and UI automation code in the same language helps engineering and QA teams level set on the critical user journeys being tested. Here we share the basics of getting started with automating an Appium test in Kotlin.
The document contains summaries of code snippets and explanations of technical concepts. It discusses:
1) How a code snippet with post-increment operator i++ would output a garbage value.
2) Why a code snippet multiplying two ints and storing in a long int variable would not give the desired output.
3) Why a code snippet attempting to concatenate a character to a string would not work.
4) How to determine the maximum number of elements an array can hold based on its data type and memory model.
5) How to read data from specific memory locations using the peekb() function.
The document contains summaries of code snippets and explanations of technical concepts. It discusses:
1) How a code snippet with post-increment operator i++ would output a garbage value.
2) Why a code snippet multiplying two ints and storing in a long int variable would not give the desired output.
3) Why a code snippet attempting to concatenate a character to a string would not work.
4) How to determine the maximum number of elements an array can hold based on its data type and memory model.
5) How to read data from specific memory locations using the peekb() function in C.
Threads, Queues, and More: Async Programming in iOSTechWell
To keep your iOS app running butter-smooth at 60 frames per second, Apple recommends doing as many tasks as possible asynchronously or “off the main thread.” Joe Keeley introduces you to some basic concepts of asynchronous programming in iOS. He discusses what threads and queues are, how they are related, and the special significance of the main queue to iOS. Look at what options are available in the iOS SDK to work asynchronously, including NSOperationQueues and Grand Central Dispatch. Take an in depth look at how to implement some common use cases for those options in Swift. Joe pays special attention to networking, one of the most common asynchronous use cases. Spend some time discussing common asynchronous programming pitfalls—and how to avoid them. Leave this session ready to try out asynchronous programming in your iOS app.
This document provides an overview of key concepts in the Java programming language, including:
- Java is an object-oriented language that is simpler than C++ and supports features like platform independence.
- The Java development environment includes tools for compiling, debugging, and running Java programs.
- Java programs work with basic data types like int and double, as well as user-defined classes, variables, and arrays.
- The document explains operators, control structures, formatting output, and the basics of classes and objects in Java.
The document provides an overview of the Open Verification Methodology (OVM) framework. OVM is a SystemVerilog library that implements object-oriented design patterns to provide base classes for verification components. It includes features for component hierarchy, configuration, phasing, reporting, transaction recording, and interfaces based on the Open System C Initiative Transaction Level Modeling 2.0 standard.
Managing gRPC Services using Kong KONNECT and the KONG API GatewayJoão Esperancinha
This document is the base for my presentation about the Kong Gateway and its usages with the gRPC plugins. The Kong gateway provides two kinds of plugins that are very crucial when thinking about working with gRPC services. There is a grpc gateway plugin and a grpc web plugin. How to work with them and how to configure them isn't difficult but some help is always good. I provide with this presentation a general look on gRPC itself and how to manage that using an API gateway.
Kuma Meshes Part I - The basics. Explaining the basics of how Meshes and Kuma Meshes work. It goes through how to get a cluster ready to start making tests with Kuma by diving into kubernetes concepts and quick installation command installations.
More Related Content
Similar to Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
This document provides information about basic input and output in Java using System.out, System.in, and the Scanner class. It discusses using print and println to display output, and how to handle input using System.in, BufferedReader, and the Scanner class. The Scanner class allows more flexible input, including the ability to test the next input, read different data types, and handle input errors.
This document provides an introduction to the Kotlin programming language through a workshop series. It discusses key Kotlin concepts like statically typed vs dynamically typed languages, features of Kotlin like being interoperable with Java, and how to write basic Kotlin code like functions, variables, types, loops, and classes. The document includes code snippets and explanations to demonstrate Kotlin syntax and best practices.
The document discusses C++ interview questions and answers related to classes, inheritance, pointers, references, and operator overloading. It provides code examples to demonstrate concepts like passing objects by value vs reference, virtual functions, and inheritance. The examples are tested on Turbo C++, Microsoft VC++ compilers under Windows environment on x86 systems.
The document summarizes several Java 5 features including generics, enhanced for loops, autoboxing/unboxing, typesafe enums, varargs, static imports, and annotations. It provides examples and explanations of each feature.
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxbradburgess22840
In Class Assignmetz/CST280W13a-1.pdf
CST 280 In-Class Practice – Week 13
Manually determine the configuration of the priority queue (stored as a heap) created
by the following operations. Trace the following logic and define the output:
enqueue(7);
enqueue(17);
enqueue(2);
enqueue(5);
enqueue(22);
enqueue(19);
enqueue(6);
enqueue(11);
enqueue(13);
write the queue contents
dequeue and write front item
enqueue(15);
enqueue(8);
dequeue and write front item
dequeue and write front item
enqueue(24);
enqueue(14);
write the queue contents
Part 2
Then, verify the output by implementing the algorithm by rewriting the priority
queue demonstration program discussed in class. Files needed:
testPQueue.cpp pqType.h heap.cpp
Deliverables
• This cover sheet (with your names on it)
• Driver source code and output for verification program exectution.
In Class Assignmetz/CST280W13b.pdf
CST 280 In-Class Practice – Week 13
Use this page as a worksheet to sketch the progression of the elements up to the first
split for the QuickSort algorithm. Use the middle array element as the split value:
15 34 99 42 11 41 66 23 55 93 48
Next, access the file quickSort.cpp from the course web page. Tailor the program
by entering the array values above in place of the integer values used for an in-class
demonstration. Be sure to adjust the index range to match the size of this array.
Remember that the parameters to the QuickSort algorithm are starting and ending index
values, not the size of the array.
Next, insert code to demonstrate the state of the array after the first split. This should
verify what you did by hand above. Insert the following code at various points within
the partition function to “see” the array at various stages of processing:
for (int i = start; i <= end; i++) // <== ADD
cout << set[i] << ' ';
cout << endl;
Insert the code at these positions:
int partition(int set[], int start, int end)
{
int pivotValue, pivotIndex, mid;
mid = (start + end) / 2;
swap(set[start], set[mid]);
pivotIndex = start;
pivotValue = set[start];
ç HERE
for (int scan = start + 1; scan <= end; scan++)
{
if (set[scan] < pivotValue)
{
pivotIndex++;
swap(set[pivotIndex], set[scan]);
}
ç HERE
}
swap(set[start], set[pivotIndex]);
ç HERE
return pivotIndex;
}
Finally, identify the line that matches what you concluded above.
Deliverables:
Deliver the following for this assignment:
• This work sheet with a sketch of the array first split
• Program source code with required change
• Program output demonstrating array configuration after first split .
01 Introduction to Kotlin - Programming in Kotlin.pptxIvanZawPhyo
Kotlin is a programming language that is expressive, concise, and portable. It runs on the Java Virtual Machine and is fully interoperable with Java. Kotlin focuses on safety, interoperability, and tooling support. The basics of Kotlin include top-level functions, variables, if/when expressions, loops, ranges, null safety features, and string templates. Kotlin avoids null pointer exceptions through language features like the Elvis operator, safe calls, and non-null types.
Kotlin is a programming language that is expressive, concise, and portable. It runs on the Java Virtual Machine and is fully interoperable with Java. Kotlin focuses on safety, interoperability, and tooling support. The basics of Kotlin include top-level functions, variables, if/when expressions, loops, ranges, null safety features, and string templates. Kotlin avoids null pointer exceptions through language features like the Elvis operator, safe calls, and non-null types.
PQTimer.java A simple driver program to run timing t.docxjoyjonna282
/* PQTimer.java
A simple driver program to run timing tests on your ArrayPQ
and BinaryHeapPQ.
Programming Assignment #2
*/
import java.util.Iterator;
import java.util.ConcurrentModificationException;
import data_structures.*;
public class PQTimer {
public static void main(String [] args) {
///////////////////////////////////////////////////////////
/// Change this variable to something smaller if timing takes too long.
final int INITIAL_SIZE = 15000;
///////////////////////////////////////////////////////////
final int ITERATIONS = 10000;
final int NUMBER_OF_STEPS = 15;
final int MAX_SIZE = INITIAL_SIZE * NUMBER_OF_STEPS +1;
final int NUMBER_OF_PRIORITIES = 20;
int size = INITIAL_SIZE;
long sequence_number = 0;
long start, stop;
int priority;
PQTestObject [] array = new PQTestObject[MAX_SIZE];
for(int i=0; i < MAX_SIZE; i++)
array[i] = new PQTestObject((int) ((10000*Math.random() %
NUMBER_OF_PRIORITIES) +1), sequence_number++);
for(int j=0; j < 15; j++) {
PriorityQueue<PQTestObject> queue =
new HeapPriorityQueue<PQTestObject>(MAX_SIZE);
queue.clear();
for(int i = 0; i < size; i++)
queue.insert(array[i]);
start = System.currentTimeMillis(); // start the timer
for(int i = 0; i < ITERATIONS; i++) {
queue.insert(array[(int)(100000*Math.random() %
MAX_SIZE)]);
queue.remove();
}
stop = System.currentTimeMillis();
System.out.println("HeapPQ, Time for n=" + size + ": " +
(stop-start));
queue.clear();
queue = new ArrayPriorityQueue<PQTestObject>(MAX_SIZE);
for(int i = 0; i < size; i++)
queue.insert(array[i]);
start = System.currentTimeMillis(); // start the timer
for(int i = 0; i < ITERATIONS; i++) {
queue.insert(array[(int)(100000*Math.random() %
MAX_SIZE)]);
queue.remove();
}
stop = System.currentTimeMillis();
System.out.println("ArrayPQ, Time for n=" + size + ": " +
(stop-start)+"\n");
size += INITIAL_SIZE;
}
}
}
/* PQTestObject.java
A simple testing object that has a priority. The sequence
number in this class is NOT the insertion sequence number
you will have in the BinaryHeapPQ class. It is only used
for verification of correct behavior, and never used in
ordering objects of this class.
*/
public class PQTestObject implements Comparable<PQTestObject> {
private int priority;
private long sequence_number;
public PQTestObject(int p, long s) {
priority = p;
sequence_number = s;
}
public int compareTo(PQTestObject o) {
return priority - o.priority;
}
public String toString() {
...
The program defines a jagged array with 3 inner arrays of unspecified length. It initializes the inner arrays. It then iterates through the jagged array and sums all elements of the inner arrays. The total sum is returned.
1. The document discusses good and bad practices for writing unit tests. It emphasizes that tests should verify the expected behavior, fail clearly when something goes wrong, and use mocks and isolation to focus on the code being tested.
2. Some examples of bad tests shown include tests that don't make assertions or assertions that don't provide useful information on failure. Real objects are also used instead of mocks, obscuring the test.
3. Good practices include using mocks to isolate the code being tested, making sure tests fail clearly when something goes wrong, and focusing tests on expected behavior through clear assertions. Automated testing, fixing broken tests, and mastering testing tools are also emphasized.
Here are some suggestions to improve the test method name:
- shouldReturnNullWhenQueryReturnsNull
- shouldPassNullFromDaoWhenQueryReturnsNull
Using "should" makes the intent clearer - we expect the method to return null under certain conditions. Describing those conditions ("when query returns null") in the name provides more context than a generic "testQuery".
Overall, test method names should clearly communicate what is being tested and under what conditions we expect the test to pass or fail. This helps readers understand the purpose and focus of each test.
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.
The document describes a problem statement to create a simple calculation module that can process arithmetic expressions. It provides the input specification using Backus-Naur Form to define the syntax. It then describes taking a simple approach to solve this without using .NET Expression Trees, including possible test failures. It includes the code for a CalcEngine class to calculate expressions and CalcEngineTest class with unit tests to validate the calculations and failures.
Kotlin is a modern programming language that focuses on clarity, code safety and conciseness. Google officially adopted Kotlin by adding support into Android Studio in 2017 and since then has announced it as the preferred language for Android developers. Android app teams have incrementally added Kotlin code to their projects or have elected to start new Android projects in Kotlin moving forward. Having the app code and UI automation code in the same language helps engineering and QA teams level set on the critical user journeys being tested. Here we share the basics of getting started with automating an Appium test in Kotlin.
The document contains summaries of code snippets and explanations of technical concepts. It discusses:
1) How a code snippet with post-increment operator i++ would output a garbage value.
2) Why a code snippet multiplying two ints and storing in a long int variable would not give the desired output.
3) Why a code snippet attempting to concatenate a character to a string would not work.
4) How to determine the maximum number of elements an array can hold based on its data type and memory model.
5) How to read data from specific memory locations using the peekb() function.
The document contains summaries of code snippets and explanations of technical concepts. It discusses:
1) How a code snippet with post-increment operator i++ would output a garbage value.
2) Why a code snippet multiplying two ints and storing in a long int variable would not give the desired output.
3) Why a code snippet attempting to concatenate a character to a string would not work.
4) How to determine the maximum number of elements an array can hold based on its data type and memory model.
5) How to read data from specific memory locations using the peekb() function in C.
Threads, Queues, and More: Async Programming in iOSTechWell
To keep your iOS app running butter-smooth at 60 frames per second, Apple recommends doing as many tasks as possible asynchronously or “off the main thread.” Joe Keeley introduces you to some basic concepts of asynchronous programming in iOS. He discusses what threads and queues are, how they are related, and the special significance of the main queue to iOS. Look at what options are available in the iOS SDK to work asynchronously, including NSOperationQueues and Grand Central Dispatch. Take an in depth look at how to implement some common use cases for those options in Swift. Joe pays special attention to networking, one of the most common asynchronous use cases. Spend some time discussing common asynchronous programming pitfalls—and how to avoid them. Leave this session ready to try out asynchronous programming in your iOS app.
This document provides an overview of key concepts in the Java programming language, including:
- Java is an object-oriented language that is simpler than C++ and supports features like platform independence.
- The Java development environment includes tools for compiling, debugging, and running Java programs.
- Java programs work with basic data types like int and double, as well as user-defined classes, variables, and arrays.
- The document explains operators, control structures, formatting output, and the basics of classes and objects in Java.
The document provides an overview of the Open Verification Methodology (OVM) framework. OVM is a SystemVerilog library that implements object-oriented design patterns to provide base classes for verification components. It includes features for component hierarchy, configuration, phasing, reporting, transaction recording, and interfaces based on the Open System C Initiative Transaction Level Modeling 2.0 standard.
Similar to Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx (20)
Managing gRPC Services using Kong KONNECT and the KONG API GatewayJoão Esperancinha
This document is the base for my presentation about the Kong Gateway and its usages with the gRPC plugins. The Kong gateway provides two kinds of plugins that are very crucial when thinking about working with gRPC services. There is a grpc gateway plugin and a grpc web plugin. How to work with them and how to configure them isn't difficult but some help is always good. I provide with this presentation a general look on gRPC itself and how to manage that using an API gateway.
Kuma Meshes Part I - The basics. Explaining the basics of how Meshes and Kuma Meshes work. It goes through how to get a cluster ready to start making tests with Kuma by diving into kubernetes concepts and quick installation command installations.
In this document I show an example of using Use-site targets in Kotlin. This is a relatively misunderstood feature of Kotlin that gets greatly overlooked by developers used to working with annotations in frameworks like the Spring Framework. The idea is that Kotlin doesn't really has a strategy to go about annotations in data classes if we don't specify the target. In Java, the target was very tangible. In Kotlin is all about abstraction. There can be negatives about this or maybe not.
Demystifying Co, Contra, In Kotlin modifier keywords.pptxJoão Esperancinha
This presentation is the backup compilation of materials used to create my video on YouTube about variance, convariance, contravariance and invariance. I aproach the topic in a different way than in the slides, but both perspectives are important to understand covariance and contravariance which are topics that can be quite convoluted. The video is located here: https://www.youtube.com/watch?v=D50Cluc2Vp4. Should you have any questions regarding this presentation please leave a comment.
The documentation to support my video about Kotlin Channels and flows that you can find here: https://www.youtube.com/watch?v=oEffjtSVAcc.
In this video and with this supporting document I am telling a story of how we can use flows and channels. To explain flows I use the examples of coffee in water and boats on the water. A pretty different example that I thought at the time would help people understand Flows and Channels in Kotlin.
This document is a presentation made for a YouTube video for my channel JESPROTECH about the evolution of tailrec through the years accross some of the most well known, and some not so known languages. The goal isn't to go through all languages ever invented, but to gain a prespective about tailrec that exists already in programming languages since the 1950's. The idea is to situate us in time and understand where we come from when we talk about tailrec and tail call optimization (TCO).
This is the document I created when I made the presentation for Eonics on Hack Night 21. Make sure to watch the document for a bit of history about Reactive programming.
The project has since moved to GitHub on https://github.com/jesperancinha/kitten-house-care-parent.
It has now been converted to Kotlin and the test branches are no longer available. If you have any questions, please post them on GitHub, or alternative post in the community on my channel jesprotech on YouTube.
KONNECT Kong-Presentation How to protect web applicationsJoão Esperancinha
This is a short presentation about different ways to use the Kong KONNECT gateway. Essentially the Kong gateway sits in front of the application we are covering with it and it can be used as a protection mechanism for our application. With KONNECT we can establish that configuration and then launch different data node planes otherwise known as Kong gateways that we can start with a specific configuration already configured in KONNECT. This is a great achievement in API gateways when it comes to unserstanding how to guarantee the safety of our applications. In KONNECT we can implement different kinds of authentication namely and mostly used, a JWT token, an apikey and OAuth2 authentications. Another way to protect our application is to establish ACL's, which are access control lists for our users which then can be assigned different permissions and there for have selective access to our applications. Another aspect of application protection is when we avoid too many requests being made at the same time to our application. In these cases, there is always the question if we are dealing with a DDoS attack or if we are dealing with a mislead user. In any case rate limiting is something that we can easily configure in Kong allowing us to turn the tap to a comfortable an acceptable installation. With KONNECT we can also configure our Kong gateways to monitor, audit and save the logs of our application. Because KONNECT gets updated and the nodes get automatically updated, the control of the updates and new version is no longer part of our plate of responsibilities. Instead, Kong KONNECT deals with that for us.
Understanding Inductive Bias in Machine LearningSUTEJAS
This presentation explores the concept of inductive bias in machine learning. It explains how algorithms come with built-in assumptions and preferences that guide the learning process. You'll learn about the different types of inductive bias and how they can impact the performance and generalizability of machine learning models.
The presentation also covers the positive and negative aspects of inductive bias, along with strategies for mitigating potential drawbacks. We'll explore examples of how bias manifests in algorithms like neural networks and decision trees.
By understanding inductive bias, you can gain valuable insights into how machine learning models work and make informed decisions when building and deploying them.
Introduction- e - waste – definition - sources of e-waste– hazardous substances in e-waste - effects of e-waste on environment and human health- need for e-waste management– e-waste handling rules - waste minimization techniques for managing e-waste – recycling of e-waste - disposal treatment methods of e- waste – mechanism of extraction of precious metal from leaching solution-global Scenario of E-waste – E-waste in India- case studies.
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELgerogepatton
As digital technology becomes more deeply embedded in power systems, protecting the communication
networks of Smart Grids (SG) has emerged as a critical concern. Distributed Network Protocol 3 (DNP3)
represents a multi-tiered application layer protocol extensively utilized in Supervisory Control and Data
Acquisition (SCADA)-based smart grids to facilitate real-time data gathering and control functionalities.
Robust Intrusion Detection Systems (IDS) are necessary for early threat detection and mitigation because
of the interconnection of these networks, which makes them vulnerable to a variety of cyberattacks. To
solve this issue, this paper develops a hybrid Deep Learning (DL) model specifically designed for intrusion
detection in smart grids. The proposed approach is a combination of the Convolutional Neural Network
(CNN) and the Long-Short-Term Memory algorithms (LSTM). We employed a recent intrusion detection
dataset (DNP3), which focuses on unauthorized commands and Denial of Service (DoS) cyberattacks, to
train and test our model. The results of our experiments show that our CNN-LSTM method is much better
at finding smart grid intrusions than other deep learning algorithms used for classification. In addition,
our proposed approach improves accuracy, precision, recall, and F1 score, achieving a high detection
accuracy rate of 99.50%.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...IJECEIAES
Climate change's impact on the planet forced the United Nations and governments to promote green energies and electric transportation. The deployments of photovoltaic (PV) and electric vehicle (EV) systems gained stronger momentum due to their numerous advantages over fossil fuel types. The advantages go beyond sustainability to reach financial support and stability. The work in this paper introduces the hybrid system between PV and EV to support industrial and commercial plants. This paper covers the theoretical framework of the proposed hybrid system including the required equation to complete the cost analysis when PV and EV are present. In addition, the proposed design diagram which sets the priorities and requirements of the system is presented. The proposed approach allows setup to advance their power stability, especially during power outages. The presented information supports researchers and plant owners to complete the necessary analysis while promoting the deployment of clean energy. The result of a case study that represents a dairy milk farmer supports the theoretical works and highlights its advanced benefits to existing plants. The short return on investment of the proposed approach supports the paper's novelty approach for the sustainable electrical system. In addition, the proposed system allows for an isolated power setup without the need for a transmission line which enhances the safety of the electrical network
ACEP Magazine edition 4th launched on 05.06.2024Rahul
This document provides information about the third edition of the magazine "Sthapatya" published by the Association of Civil Engineers (Practicing) Aurangabad. It includes messages from current and past presidents of ACEP, memories and photos from past ACEP events, information on life time achievement awards given by ACEP, and a technical article on concrete maintenance, repairs and strengthening. The document highlights activities of ACEP and provides a technical educational article for members.
Embedded machine learning-based road conditions and driving behavior monitoringIJECEIAES
Car accident rates have increased in recent years, resulting in losses in human lives, properties, and other financial costs. An embedded machine learning-based system is developed to address this critical issue. The system can monitor road conditions, detect driving patterns, and identify aggressive driving behaviors. The system is based on neural networks trained on a comprehensive dataset of driving events, driving styles, and road conditions. The system effectively detects potential risks and helps mitigate the frequency and impact of accidents. The primary goal is to ensure the safety of drivers and vehicles. Collecting data involved gathering information on three key road events: normal street and normal drive, speed bumps, circular yellow speed bumps, and three aggressive driving actions: sudden start, sudden stop, and sudden entry. The gathered data is processed and analyzed using a machine learning system designed for limited power and memory devices. The developed system resulted in 91.9% accuracy, 93.6% precision, and 92% recall. The achieved inference time on an Arduino Nano 33 BLE Sense with a 32-bit CPU running at 64 MHz is 34 ms and requires 2.6 kB peak RAM and 139.9 kB program flash memory, making it suitable for resource-constrained embedded systems.
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
NATURAL DEEP EUTECTIC SOLVENTS AS ANTI-FREEZING AGENT
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
1. Decoding Kotlin -
Your guide to
solving the
mysterious in
Kotlin
By João Esperancinha 2024/04/24
2. Nullability
1. Working with the Spring Framework
2. Reflection to force nulls
Inline and cross-inline
1. The Java overview
Tail recursive => Tail Cal Optimization
(TCO)
1. What is it
2. Why?
3. How it makes us work recursively
and not use mutable
Data classes
1. Why things work and why things
don't work
2. How to fix the ones that don't
3. How to work with use-site targets.
What does a `delegate` do? and other
use-site targets.
Topics for today
3. Nullability
Kotlin promises a guarantee of
null-safety. Although we can use
nullable members in our classes,
we really shouldn’t whenever
possible.
Whenever possible?
4. @Table(name = "CAR_PARTS")
@Entity
data class CarPart(
@Id
val id: Long,
val name: String,
val productionDate: Instant,
val expiryDate: Instant,
val barCode: Long,
val cost: BigDecimal
)
CREATE SEQUENCE car_parts_id_sequence
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
CREATE TABLE CAR_PARTS (
id BIGINT NOT NULL DEFAULT
nextval('car_parts_id_sequence'::regclass)
,
name VARCHAR(100),
production_date timestamp,
expiry_date timestamp,
bar_code BIGINT,
cost float
);
CRUD Entity Example
5. CRUD Entity Example
INSERT INTO CAR_PARTS
(name, production_date, expiry_date, bar_code, cost)
VALUES ('screw', current_date, current_date, 12345, 1.2);
INSERT INTO CAR_PARTS
(name, production_date, expiry_date, bar_code, cost)
VALUES (null, current_date, current_date, 12345, 1.2);
@Test
fun `should mysteriously get a list with a
car part with a name null`() {
carPartDao.findAll()
.filter { it.name == null }
.shouldHaveSize(1)
}
Is this
possible?
6. Reflection Example
val carPartDto = CarPartDto(
id = 123L,
name = "name",
productionDate = Instant.now(),
expiryDate = Instant.now(),
cost = BigDecimal.TEN,
barCode = 1234L
)
println(carPartDto)
val field: Field = CarPartDto::class.java
.getDeclaredField("name")
field.isAccessible = true
field.set(carPartDto, null)
println(carPartDto)
assert(carPartDto.name == null)
println(carPartDto.name == null)
data class CarPartDto(
val id: Long,
val name: String,
val productionDate:
Instant,
val expiryDate: Instant,
val barCode: Long,
val cost: BigDecimal
)
Is this
possible?
7. Inline and
crossinline.
Inline and crossline can be used in
combination with each other.
Inline provides bytecode copies of
the code per each call point and
they can even help avoid type
erasure. Crossinline improves
readability and some safety, but
nothing really functional.
Why does this
matter?
8. Crossinline as just a marker
fun main() {
callEngineCrossInline {
println("Place key in ignition")
println("Turn key or press push button ignition")
println("Clutch to the floor")
println("Set the first gear")
}.run { println(this) }
}
inline fun callEngineCrossInline(startManually: () -> Unit) {
run loop@{
println("This is the start of the loop.")
introduction {
println("Get computer in the backseat")
return@introduction
}
println("This is the end of the loop.")
}
println("Engine started!")
}
fun introduction(intro: () -> Unit) {
println(LocalDateTime.now())
intro()
return
}
public final class IsolatedCarPartsExampleKt {
public static final void main() {
int $i$f$callEngineCrossInline = false;
int var1 = false;
String var2 = "This is the start of the loop.";
System.out.println(var2);
introduction((Function0)IsolatedCarPartsExampleKt$ca
llEngineCrossInline$1$1.INSTANCE);
var2 = "This is the end of the loop.";
System.out.println(var2);
String var4 = "Engine started!";
System.out.println(var4);
Unit var3 = Unit.INSTANCE;
int var5 = false;
System.out.println(var3);
}
public static final void introduction(@NotNull
Function0 intro) {
Intrinsics.checkNotNullParameter(intro,
"intro");
LocalDateTime var1 = LocalDateTime.now();
System.out.println(var1);
intro.invoke();
} public final void invoke() {
String var1 = "Get computer in the
backseat";
System.out.println(var1);
}
Decompiled
code
9. Crossinline as just a marker
fun main() {
callEngineCrossInline {
println("Place key in ignition")
println("Turn key or press pus button ignition")
println("Clutch to the floor")
println("Set the first gear")
}.run { println(this) }
}
inline fun callEngineCrossInline(crossinline startManually: () -
> Unit) {
run loop@{
println("This is the start of the loop.")
introduction {
println("Get computer in the backseat")
startManually()
return@introduction
}
println("This is the end of the loop.")
}
println("Engine started!")
}
fun introduction(intro: () -> Unit) {
println(LocalDateTime.now())
intro()
return
}
public final class IsolatedCarPartsExampleKt {
public static final void main() {
int $i$f$callEngineCrossInline = false;
int var1 = false;
String var2 = "This is the start of the loop.";
System.out.println(var2);
introduction((Function0)(new
IsolatedCarPartsExampleKt$main$$inlined$callEngineCr
ossInline$1()));
var2 = "This is the end of the loop.";
System.out.println(var2);
String var4 = "Engine started!";
System.out.println(var4);
Unit var3 = Unit.INSTANCE;
int var5 = false;
System.out.println(var3);
}
public static final void introduction(@NotNull
Function0 intro) {
Intrinsics.checkNotNullParameter(intro,
"intro");
LocalDateTime var1 = LocalDateTime.now();
System.out.println(var1);
intro.invoke();
}
public final void invoke() {
String var1 = "Get computer in the
backseat";
System.out.println(var1);
int var2 = false;
String var3 = "Place key in ignition";
System.out.println(var3);
var3 = "Turn key or press push button
ignition";
System.out.println(var3);
var3 = "Clutch to the floor";
System.out.println(var3);
var3 = "Set the first gear";
System.out.println(var3);
}
Decompiled
code
11. Tail Call
Optimization
Since the late 50’s TCO was
already a theory intentend to be
applied to Tail Recursivity. It
allows tail recursive functions to
be transformed into iterative
functions in the compiled code for
better performance.
What is the catch?
12. Tail Call Optimization
sealed interface Part {
val totalWeight: Double
}
sealed interface ComplexPart : Part{
val parts: List<Part>
}
data class CarPart(val name: String, val weight:
Double) : Part {
override val totalWeight: Double
get() = weight
}
data class ComplexCarPart(
val name: String,
val weight: Double,
override val parts: List<Part>
) :
ComplexPart {
override val totalWeight: Double
get() = weight
}
data class Car(
val name: String,
override val parts: List<Part>
) : ComplexPart {
override val totalWeight: Double
get() = parts.sumOf { it.totalWeight }
}
tailrec fun totalWeight(parts: List<Part>, acc: Double =
0.0): Double {
if (parts.isEmpty()) {
return acc
}
val part = parts.first()
val remainingParts = parts.drop(1)
val currentWeight = acc + part.totalWeight
return when (part) {
is ComplexPart -> totalWeight(remainingParts +
part.parts, currentWeight)
else -> totalWeight(remainingParts, currentWeight)
}
}
Why use this?
All variables
are immutable
Tail recursive
13. Tail Call Optimization
tailrec fun totalWeight(parts: List<Part>, acc: Double =
0.0): Double {
if (parts.isEmpty()) {
return acc
}
val part = parts.first()
val remainingParts = parts.drop(1)
val currentWeight = acc + part.totalWeight
return when (part) {
is ComplexPart -> totalWeight(remainingParts +
part.parts, currentWeight)
else -> totalWeight(remainingParts, currentWeight)
}
}
public static final double totalWeight(@NotNull List parts, double acc) {
while(true) {
Intrinsics.checkNotNullParameter(parts, "parts");
if (parts.isEmpty()) {
return acc;
}
Part part = (Part)CollectionsKt.first(parts);
List remainingParts = CollectionsKt.drop((Iterable)parts, 1);
double currentWeight = acc + part.getTotalWeight();
if (part instanceof ComplexPart) {
List var10000 = CollectionsKt.plus((Collection)remainingParts,
(Iterable)((ComplexPart)part).getParts());
acc = currentWeight;
parts = var10000;
} else {
acc = currentWeight;
parts = remainingParts;
}
}
}
Variables are
mutable and
algorithm is
iterative
14. Data classes and
Frameworks
Kotlin provides use-site targets
that allow us to specify where
particular annotations have to be
applied. Sometimes we need them
and sometimes we don’t
Why?
15. Working with Data classes
@Table(name = "CAR_PARTS")
@Entity
data class CarPart(
@Id
val id: Long,
@Column
@field:NotNull
@field:Size(min=3, max=20)
val name: String,
val productionDate: Instant,
val expiryDate: Instant,
val barCode: Long,
@field:Min(value = 5)
val cost: BigDecimal
)
@Table(name = "CAR_PARTS")
@Entity
data class CarPart(
@Id
val id: Long,
@Column
@NotNull
@Size(min=3, max=20)
val name: String,
val productionDate: Instant,
val expiryDate: Instant,
val barCode: Long,
@Min(value = 5)
val cost: BigDecimal
)
Doesn’t work Works!
Why
use-site
targets?
16. Working with Data classes
https://kotlinlang.org/docs/annotations.html#annotation-use-site-targets
If you don't specify a use-site target, the target is chosen
according to the @Target annotation of the annotation
being used. If there are multiple applicable targets, the first
applicable target from the following list is used:
● param
● property
● field
17. Working with Data classes
@Target({ElementType.METHOD,
ElementType.FIELD,
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.PARAMETER,
ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(List.class)
@Documented
@Constraint(
validatedBy = {}
)
public @interface Size {
PARAMETER
is
selected
18. Working with Data classes
public final class CarPart {
@Id
private final long id;
@Column
@NotNull
private final String name;
@NotNull
private final Instant productionDate;
@NotNull
private final Instant expiryDate;
private final long barCode;
@NotNull
private final BigDecimal cost;
public final long getId() {
return this.id;
}
@NotNull
public final String getName() {
return this.name;
}
@NotNull
public final Instant getProductionDate() {
return this.productionDate;
}
@NotNull
public final Instant getExpiryDate() {
return this.expiryDate;
}
public final long getBarCode() {
return this.barCode;
}
@NotNull
public final BigDecimal getCost() {
return this.cost;
}
public CarPart(long id, @jakarta.validation.constraints.NotNull @Size(min =
3,max = 20) @NotNull String name, @NotNull Instant productionDate, @NotNull
Instant expiryDate, long barCode, @Min(5L) @NotNull BigDecimal cost) {
Intrinsics.checkNotNullParameter(name, "name");
Intrinsics.checkNotNullParameter(productionDate, "productionDate");
Intrinsics.checkNotNullParameter(expiryDate, "expiryDate");
Intrinsics.checkNotNullParameter(cost, "cost");
Not where we want
them to be,
but where they are
expected
19. @Table(name = "CAR_PARTS")
@Entity
data class CarPart(
@Id
val id: Long,
@Column
@field:NotNull
@field:Size(min=3, max=20)
val name: String,
val productionDate: Instant,
val expiryDate: Instant,
val barCode: Long,
@field:Min(value = 5)
val cost: BigDecimal
)
Working with Data classes
public final class CarPart {
@Id
private final long id;
@Column
@NotNull
@Size(
min = 3,
max = 20
)
@org.jetbrains.annotations.NotNull
private final String name;
@org.jetbrains.annotations.NotNull
private final Instant productionDate;
@org.jetbrains.annotations.NotNull
private final Instant expiryDate;
private final long barCode;
@Min(5L)
@org.jetbrains.annotations.NotNull
private final BigDecimal cost;
Since @field forces
the target, these
annotations get
applied where they
should
21. Working with Delegates
interface Horn {
fun beep()
}
class CarHorn : Horn {
override fun beep() {
println("beep!")
}
}
class WagonHorn : Horn {
override fun beep() {
println("bwooooooo!")
}
}
annotation class DelegateToWagonHorn
annotation class DelegateToCarHorn
class SoundDelegate(private val initialHorn: Horn) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): Horn {
return initialHorn
}
}
class HornPack {
@delegate:DelegateToWagonHorn
val wagonHorn: Horn by SoundDelegate(CarHorn())
@delegate:DelegateToCarHorn
val carHorn: Horn by SoundDelegate(WagonHorn())
}
Where is this being applied
to?
Horn or SoundDelegate?
22. Working with Delegates
public final class HornPack {
// $FF: synthetic field
static final KProperty[] $$delegatedProperties = new KProperty[]{Reflection.property1(new
PropertyReference1Impl(HornPack.class, "wagonHorn", "getWagonHorn()Lorg/jesperancinha/talks/carparts/Horn;",
0)), Reflection.property1(new PropertyReference1Impl(HornPack.class, "carHorn",
"getCarHorn()Lorg/jesperancinha/talks/carparts/Horn;", 0))};
@DelegateToWagonHorn
@NotNull
private final SoundDelegate wagonHorn$delegate = new SoundDelegate((Horn)(new CarHorn()));
@DelegateToCarHorn
@NotNull
private final SoundDelegate carHorn$delegate = new SoundDelegate((Horn)(new WagonHorn()));
@NotNull
public final Horn getWagonHorn() {
return this.wagonHorn$delegate.getValue(this, $$delegatedProperties[0]);
}
@NotNull
public final Horn getCarHorn() {
return this.carHorn$delegate.getValue(this, $$delegatedProperties[1]);
}
}
SoundDelegate
No Horn!
23. Working with Delegates
class SanitizedName(var name: String?) {
operator fun getValue(thisRef: Any?,
property: KProperty<*>): String? = name
operator fun setValue(thisRef: Any?,
property: KProperty<*>, v: String?) {
name = v?.trim()
}
}
class PartNameDto {
@get:NotBlank
@get:Size(max = 12)
var name: String? by SanitizedName(null)
override fun toString(): String {
return name ?: "N/A"
}
}
class ImpossiblePartNameDto {
@delegate:NotBlank
@delegate:Size(max = 12)
var name: String? by SanitizedName(null)
override fun toString(): String {
return name ?: "N/A"
}
}
public final class PartNameDto {
static final KProperty[] $$delegatedProperties = new KProperty[]{Reflection.mutableProperty1(new
MutablePropertyReference1Impl(PartNameDto.class, "name", "getName()Ljava/lang/String;", 0))};
@Nullable
private final SanitizedName name$delegate = new SanitizedName((String)null);
@NotBlank
@Size(
max = 12
)
@Nullable
public final String getName() {
return this.name$delegate.getValue(this, $$delegatedProperties[0]);
}
…
public final class ImpossiblePartNameDto {
static final KProperty[] $$delegatedProperties = new KProperty[]{Reflection.mutableProperty1(new
MutablePropertyReference1Impl(ImpossiblePartNameDto.class, "name", "getName()Ljava/lang/String;",
0))};
@NotBlank
@Size(
max = 12
)
@Nullable
private final SanitizedName name$delegate = new SanitizedName((String)null);
@Nullable
public final String getName() {
return this.name$delegate.getValue(this, $$delegatedProperties[0]);
}
24. Working with Delegates
@Service
data class DelegationService(
val id: UUID = UUID.randomUUID()
) {
@delegate:LocalDateTimeValidatorConstraint
@get: Past
val currentDate: LocalDateTime by LocalDateTimeDelegate()
}
public class DelegationService {
// $FF: synthetic field
static final KProperty[] $$delegatedProperties = new KProperty[]{Reflection.property1(new
PropertyReference1Impl(DelegationService.class, "currentDate",
"getCurrentDate()Ljava/time/LocalDateTime;", 0))};
@LocalDateTimeValidatorConstraint
@NotNull
private final LocalDateTimeDelegate currentDate$delegate;
@NotNull
private final UUID id;
@Past
@NotNull
public LocalDateTime getCurrentDate() {
return this.currentDate$delegate.getValue(this, $$delegatedProperties[0]);
}
25. What’s next?
➔ Better understanding of the Kotlin Language.
➔ Don’t fight the Spring Framework or anything else like Quarkus. They are not evil and they are not
magic.
➔ Read the Kotlin documentation and only use Google as a last resort.
➔ Nothing is perfect and Kotlin also falls into that category and recognizing that, allow us to be
better.