Update javaxval/src/test/java/org/baeldung/javaxval/messageinterpolator/ParameterMessageInterpolaterIntegrationTest.java

update to use the givenX_whenY_thenZ naming convention for tests

Co-Authored-By: KevinGilmore <kpg102@gmail.com>
This commit is contained in:
Yavuz Tas
2019-10-29 10:02:27 +01:00
committed by GitHub
parent db85c8f275
commit e28fd3e7c9
20479 changed files with 1642089 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
/bin/
#ignore gradle
.gradle/
#ignore build and generated files
build/
node/
out/
#ignore installed node modules and package lock file
node_modules/
package-lock.json
+63
View File
@@ -0,0 +1,63 @@
## Core Kotlin
This module contains articles about core Kotlin.
### Relevant articles:
- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin)
- [Guide to the “when{}” Block in Kotlin](https://www.baeldung.com/kotlin-when)
- [Comprehensive Guide to Null Safety in Kotlin](https://www.baeldung.com/kotlin-null-safety)
- [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability)
- [Difference Between “==” and “===” operators in Kotlin](https://www.baeldung.com/kotlin-equality-operators)
- [Generics in Kotlin](https://www.baeldung.com/kotlin-generics)
- [Introduction to Kotlin Coroutines](https://www.baeldung.com/kotlin-coroutines)
- [Destructuring Declarations in Kotlin](https://www.baeldung.com/kotlin-destructuring-declarations)
- [Lazy Initialization in Kotlin](https://www.baeldung.com/kotlin-lazy-initialization)
- [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api)
- [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map)
- [Data Classes in Kotlin](https://www.baeldung.com/kotlin-data-classes)
- [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties)
- [Sealed Classes in Kotlin](https://www.baeldung.com/kotlin-sealed-classes)
- [JUnit 5 for Kotlin Developers](https://www.baeldung.com/junit-5-kotlin)
- [Extension Methods in Kotlin](https://www.baeldung.com/kotlin-extension-methods)
- [Infix Functions in Kotlin](https://www.baeldung.com/kotlin-infix-functions)
- [Try-with-resources in Kotlin](https://www.baeldung.com/kotlin-try-with-resources)
- [Regular Expressions in Kotlin](https://www.baeldung.com/kotlin-regular-expressions)
- [Objects in Kotlin](https://www.baeldung.com/kotlin-objects)
- [Reading from a File in Kotlin](https://www.baeldung.com/kotlin-read-file)
- [Guide to Kotlin @JvmField](https://www.baeldung.com/kotlin-jvm-field-annotation)
- [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection)
- [Writing to a File in Kotlin](https://www.baeldung.com/kotlin-write-file)
- [Lambda Expressions in Kotlin](https://www.baeldung.com/kotlin-lambda-expressions)
- [Kotlin String Templates](https://www.baeldung.com/kotlin-string-template)
- [Working with Enums in Kotlin](https://www.baeldung.com/kotlin-enum)
- [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project)
- [Reflection with Kotlin](https://www.baeldung.com/kotlin-reflection)
- [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number)
- [Idiomatic Logging in Kotlin](https://www.baeldung.com/kotlin-logging)
- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors)
- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern)
- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes)
- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant)
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
- [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings)
- [Kotlin return, break, continue Keywords](https://www.baeldung.com/kotlin-return-break-continue)
- [Mapping of Data Objects in Kotlin](https://www.baeldung.com/kotlin-data-objects)
- [Initializing Arrays in Kotlin](https://www.baeldung.com/kotlin-initialize-array)
- [Threads vs Coroutines in Kotlin](https://www.baeldung.com/kotlin-threads-coroutines)
- [Guide to Kotlin Interfaces](https://www.baeldung.com/kotlin-interfaces)
- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort)
- [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt)
- [Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree)
- [Generate a Random Alphanumeric String in Kotlin](https://www.baeldung.com/kotlin-random-alphanumeric-string)
- [Kotlin Contracts](https://www.baeldung.com/kotlin-contracts)
- [Operator Overloading in Kotlin](https://www.baeldung.com/kotlin-operator-overloading)
- [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes)
- [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final)
- [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach)
- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl)
- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods)
- [Inline Functions in Kotlin](https://www.baeldung.com/kotlin-inline-functions)
- [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern)
- More articles: [[next -->]](/core-kotlin-2)
+48
View File
@@ -0,0 +1,48 @@
group 'com.baeldung.ktor'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.2.41'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName = 'APIServer.kt'
sourceCompatibility = 1.8
compileKotlin { kotlinOptions.jvmTarget = "1.8" }
compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
kotlin { experimental { coroutines "enable" } }
repositories {
mavenCentral()
jcenter()
maven { url "https://dl.bintray.com/kotlin/ktor" }
}
sourceSets {
main{
kotlin{
srcDirs 'com/baeldung/ktor'
}
}
}
dependencies {
compile "ch.qos.logback:logback-classic:1.2.1"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
BIN
View File
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip
Vendored Executable
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
Vendored Executable
+84
View File
@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+87
View File
@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-kotlin</artifactId>
<name>core-kotlin</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-kotlin</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../parent-kotlin</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>com.github.kittinunf.fuel</groupId>
<artifactId>fuel</artifactId>
<version>${fuel.version}</version>
</dependency>
<dependency>
<groupId>com.github.kittinunf.fuel</groupId>
<artifactId>fuel-gson</artifactId>
<version>${fuel.version}</version>
</dependency>
<dependency>
<groupId>com.github.kittinunf.fuel</groupId>
<artifactId>fuel-rxjava</artifactId>
<version>${fuel.version}</version>
</dependency>
<dependency>
<groupId>com.github.kittinunf.fuel</groupId>
<artifactId>fuel-coroutines</artifactId>
<version>${fuel.version}</version>
</dependency>
<dependency>
<groupId>nl.komponents.kovenant</groupId>
<artifactId>kovenant</artifactId>
<version>${kovenant.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>uy.kohesive.injekt</groupId>
<artifactId>injekt-core</artifactId>
<version>${injekt-core.version}</version>
</dependency>
</dependencies>
<properties>
<commons-math3.version>3.6.1</commons-math3.version>
<junit.platform.version>1.1.1</junit.platform.version>
<junit.vintage.version>5.2.0</junit.vintage.version>
<assertj.version>3.10.0</assertj.version>
<fuel.version>1.15.0</fuel.version>
<kovenant.version>3.3.0</kovenant.version>
<injekt-core.version>1.16.1</injekt-core.version>
</properties>
</project>
+11
View File
@@ -0,0 +1,11 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
+2
View File
@@ -0,0 +1,2 @@
rootProject.name = 'KtorWithKotlin'
@@ -0,0 +1,17 @@
package com.baeldung.constructor
class Car {
val id: String
val type: String
constructor(id: String, type: String) {
this.id = id
this.type = type
}
}
fun main(args: Array<String>) {
val car = Car("1", "sport")
val s= Car("2", "suv")
}
@@ -0,0 +1,3 @@
package com.baeldung.constructor
class Employee(name: String, val salary: Int): Person(name)
@@ -0,0 +1,19 @@
package com.baeldung.constructor;
class PersonJava {
final String name;
final String surname;
final Integer age;
public PersonJava(String name, String surname) {
this.name = name;
this.surname = surname;
this.age = null;
}
public PersonJava(String name, String surname, Integer age) {
this.name = name;
this.surname = surname;
this.age = age;
}
}
@@ -0,0 +1,88 @@
package com.baeldung.dataclass;
public class Movie {
private String name;
private String studio;
private float rating;
public Movie(String name, String studio, float rating) {
this.name = name;
this.studio = studio;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudio() {
return studio;
}
public void setStudio(String studio) {
this.studio = studio;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(rating);
result = prime * result + ((studio == null) ? 0 : studio.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Movie other = (Movie) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Float.floatToIntBits(rating) != Float.floatToIntBits(other.rating))
return false;
if (studio == null) {
if (other.studio != null)
return false;
} else if (!studio.equals(other.studio))
return false;
return true;
}
@Override
public String toString() {
return "Movie [name=" + name + ", studio=" + studio + ", rating=" + rating + "]";
}
}
@@ -0,0 +1,24 @@
package com.baeldung.java;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ArrayExample {
public int sumValues(int[] nums) {
int res = 0;
for (int x:nums) {
res += x;
}
return res;
}
public void writeList() throws IOException {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
fr.close();
}
}
@@ -0,0 +1,24 @@
package com.baeldung.java;
public class Customer {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
@@ -0,0 +1,7 @@
package com.baeldung.java;
public class StringUtils {
public static String toUpperCase(String name) {
return name.toUpperCase();
}
}
@@ -0,0 +1,14 @@
package com.baeldung.lazy;
public class ClassWithHeavyInitialization {
private ClassWithHeavyInitialization() {
}
private static class LazyHolder {
public static final ClassWithHeavyInitialization INSTANCE = new ClassWithHeavyInitialization();
}
public static ClassWithHeavyInitialization getInstance() {
return LazyHolder.INSTANCE;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.mavenjavakotlin;
import com.baeldung.mavenjavakotlin.services.JavaService;
import com.baeldung.mavenjavakotlin.services.KotlinService;
public class Application {
private static final String JAVA = "java";
private static final String KOTLIN = "kotlin";
public static void main(String[] args) {
String language = args[0];
switch (language) {
case JAVA:
new JavaService().sayHello();
break;
case KOTLIN:
new KotlinService().sayHello();
break;
default:
// Do nothing
break;
}
}
}
@@ -0,0 +1,9 @@
package com.baeldung.mavenjavakotlin.services;
public class JavaService {
public void sayHello() {
System.out.println("Java says 'Hello World!'");
}
}
@@ -0,0 +1,22 @@
package com.baeldung.builder
class FoodOrder private constructor(
val bread: String?,
val condiments: String?,
val meat: String?,
val fish: String?
) {
data class Builder(
var bread: String? = null,
var condiments: String? = null,
var meat: String? = null,
var fish: String? = null) {
fun bread(bread: String) = apply { this.bread = bread }
fun condiments(condiments: String) = apply { this.condiments = condiments }
fun meat(meat: String) = apply { this.meat = meat }
fun fish(fish: String) = apply { this.fish = fish }
fun build() = FoodOrder(bread, condiments, meat, fish)
}
}
@@ -0,0 +1,8 @@
package com.baeldung.builder
class FoodOrderApply {
var bread: String? = null
var condiments: String? = null
var meat: String? = null
var fish: String? = null
}
@@ -0,0 +1,7 @@
package com.baeldung.builder
data class FoodOrderNamed(
val bread: String? = null,
val condiments: String? = null,
val meat: String? = null,
val fish: String? = null)
@@ -0,0 +1,9 @@
package com.baeldung.builder
fun main(args: Array<String>) {
FoodOrder.Builder()
.bread("bread")
.condiments("condiments")
.meat("meat")
.fish("bread").let { println(it) }
}
@@ -0,0 +1,26 @@
package com.baeldung.constructor
open class Person(
val name: String,
val age: Int? = null
) {
val upperCaseName: String = name.toUpperCase()
init {
println("Hello, I'm $name")
if (age != null && age < 0) {
throw IllegalArgumentException("Age cannot be less than zero!")
}
}
init {
println("upperCaseName is $upperCaseName")
}
}
fun main(args: Array<String>) {
val person = Person("John")
val personWithAge = Person("John", 22)
}
@@ -0,0 +1,23 @@
package com.baeldung.contract
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@ExperimentalContracts
inline fun <R> myRun(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
@ExperimentalContracts
fun callsInPlace() {
val i: Int
myRun {
i = 1 // Without contract initialization is forbidden due to possible re-assignment
}
println(i) // Without contract variable might be uninitialized
}
@@ -0,0 +1,43 @@
package com.baeldung.contract
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
data class Request(val arg: String)
class Service {
@ExperimentalContracts
fun process(request: Request?) {
validate(request)
println(request.arg)
}
}
@ExperimentalContracts
private fun validate(request: Request?) {
contract {
returns() implies (request != null)
}
if (request == null) {
throw IllegalArgumentException("Undefined request")
}
}
data class MyEvent(val message: String)
@ExperimentalContracts
fun processEvent(event: Any?) {
if (isInterested(event)) {
println(event.message) // Compiler makes smart cast here with the help of contract
}
}
@ExperimentalContracts
fun isInterested(event: Any?): Boolean {
contract {
returns(true) implies (event is MyEvent)
}
return event is MyEvent
}
@@ -0,0 +1,3 @@
package com.baeldung.dataclass
data class Movie(val name: String, val studio: String, var rating: Float)
@@ -0,0 +1,26 @@
package com.baeldung.dataclass
fun main(args: Array<String>) {
val movie = Movie("Whiplash", "Sony Pictures", 8.5F)
println(movie.name) //Whiplash
println(movie.studio) //Sony Pictures
println(movie.rating) //8.5
movie.rating = 9F
println(movie.toString()) //Movie(name=Whiplash, studio=Sony Pictures, rating=9.0)
val betterRating = movie.copy(rating = 9.5F)
println(betterRating.toString()) //Movie(name=Whiplash, studio=Sony Pictures, rating=9.5)
movie.component1() //name
movie.component2() //studio
movie.component3() //rating
val(name, studio, rating) = movie
fun getMovieInfo() = movie
val(namef, studiof, ratingf) = getMovieInfo()
}
@@ -0,0 +1,10 @@
package com.baeldung.datamapping
data class User(
val firstName: String,
val lastName: String,
val street: String,
val houseNumber: String,
val phone: String,
val age: Int,
val password: String)
@@ -0,0 +1,22 @@
package com.baeldung.datamapping
import kotlin.reflect.full.memberProperties
fun User.toUserView() = UserView(
name = "$firstName $lastName",
address = "$street $houseNumber",
telephone = phone,
age = age
)
fun User.toUserViewReflection() = with(::UserView) {
val propertiesByName = User::class.memberProperties.associateBy { it.name }
callBy(parameters.associate { parameter ->
parameter to when (parameter.name) {
UserView::name.name -> "$firstName $lastName"
UserView::address.name -> "$street $houseNumber"
UserView::telephone.name -> phone
else -> propertiesByName[parameter.name]?.get(this@toUserViewReflection)
}
})
}
@@ -0,0 +1,8 @@
package com.baeldung.datamapping
data class UserView(
val name: String,
val address: String,
val telephone: String,
val age: Int
)
@@ -0,0 +1,19 @@
package com.baeldung.datastructures
/**
* Example of how to use the {@link Node} class.
*
*/
fun main(args: Array<String>) {
val tree = Node(4)
val keys = arrayOf(8, 15, 21, 3, 7, 2, 5, 10, 2, 3, 4, 6, 11)
for (key in keys) {
tree.insert(key)
}
val node = tree.find(4)!!
println("Node with value ${node.key} [left = ${node.left?.key}, right = ${node.right?.key}]")
println("Delete node with key = 3")
node.delete(3)
print("Tree content after the node elimination: ")
println(tree.visit().joinToString { it.toString() })
}
@@ -0,0 +1,167 @@
package com.baeldung.datastructures
/**
* An ADT for a binary search tree.
* Note that this data type is neither immutable nor thread safe.
*/
class Node(
var key: Int,
var left: Node? = null,
var right: Node? = null) {
/**
* Return a node with given value. If no such node exists, return null.
* @param value
*/
fun find(value: Int): Node? = when {
this.key > value -> left?.find(value)
this.key < value -> right?.find(value)
else -> this
}
/**
* Insert a given value into the tree.
* After insertion, the tree should contain a node with the given value.
* If the tree already contains the given value, nothing is performed.
* @param value
*/
fun insert(value: Int) {
if (value > this.key) {
if (this.right == null) {
this.right = Node(value)
} else {
this.right?.insert(value)
}
} else if (value < this.key) {
if (this.left == null) {
this.left = Node(value)
} else {
this.left?.insert(value)
}
}
}
/**
* Delete the value from the given tree. If the tree does not contain the value, the tree remains unchanged.
* @param value
*/
fun delete(value: Int) {
when {
value > key -> scan(value, this.right, this)
value < key -> scan(value, this.left, this)
else -> removeNode(this, null)
}
}
/**
* Scan the tree in the search of the given value.
* @param value
* @param node sub-tree that potentially might contain the sought value
* @param parent node's parent
*/
private fun scan(value: Int, node: Node?, parent: Node?) {
if (node == null) {
System.out.println("value " + value
+ " seems not present in the tree.")
return
}
when {
value > node.key -> scan(value, node.right, node)
value < node.key -> scan(value, node.left, node)
value == node.key -> removeNode(node, parent)
}
}
/**
* Remove the node.
*
* Removal process depends on how many children the node has.
*
* @param node node that is to be removed
* @param parent parent of the node to be removed
*/
private fun removeNode(node: Node, parent: Node?) {
node.left?.let { leftChild ->
run {
node.right?.let {
removeTwoChildNode(node)
} ?: removeSingleChildNode(node, leftChild)
}
} ?: run {
node.right?.let { rightChild -> removeSingleChildNode(node, rightChild) } ?: removeNoChildNode(node, parent)
}
}
/**
* Remove the node without children.
* @param node
* @param parent
*/
private fun removeNoChildNode(node: Node, parent: Node?) {
parent?.let { p ->
if (node == p.left) {
p.left = null
} else if (node == p.right) {
p.right = null
}
} ?: throw IllegalStateException(
"Can not remove the root node without child nodes")
}
/**
* Remove a node that has two children.
*
* The process of elimination is to find the biggest key in the left sub-tree and replace the key of the
* node that is to be deleted with that key.
*/
private fun removeTwoChildNode(node: Node) {
val leftChild = node.left!!
leftChild.right?.let {
val maxParent = findParentOfMaxChild(leftChild)
maxParent.right?.let {
node.key = it.key
maxParent.right = null
} ?: throw IllegalStateException("Node with max child must have the right child!")
} ?: run {
node.key = leftChild.key
node.left = leftChild.left
}
}
/**
* Return a node whose right child contains the biggest value in the given sub-tree.
* Assume that the node n has a non-null right child.
*
* @param n
*/
private fun findParentOfMaxChild(n: Node): Node {
return n.right?.let { r -> r.right?.let { findParentOfMaxChild(r) } ?: n }
?: throw IllegalArgumentException("Right child must be non-null")
}
/**
* Remove a parent that has only one child.
* Removal is effectively is just coping the data from the child parent to the parent parent.
* @param parent Node to be deleted. Assume that it has just one child
* @param child Assume it is a child of the parent
*/
private fun removeSingleChildNode(parent: Node, child: Node) {
parent.key = child.key
parent.left = child.left
parent.right = child.right
}
fun visit(): Array<Int> {
val a = left?.visit() ?: emptyArray()
val b = right?.visit() ?: emptyArray()
return a + arrayOf(key) + b
}
}
@@ -0,0 +1,15 @@
package com.baeldung.datetime
import java.time.Duration
import java.time.LocalTime
class UseDuration {
fun modifyDates(localTime: LocalTime, duration: Duration): LocalTime {
return localTime.plus(duration)
}
fun getDifferenceBetweenDates(localTime1: LocalTime, localTime2: LocalTime): Duration {
return Duration.between(localTime1, localTime2)
}
}
@@ -0,0 +1,42 @@
package com.baeldung.datetime
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import java.time.temporal.TemporalAdjusters
class UseLocalDate {
fun getLocalDateUsingFactoryOfMethod(year: Int, month: Int, dayOfMonth: Int): LocalDate {
return LocalDate.of(year, month, dayOfMonth)
}
fun getLocalDateUsingParseMethod(representation: String): LocalDate {
return LocalDate.parse(representation)
}
fun getLocalDateFromClock(): LocalDate {
return LocalDate.now()
}
fun getNextDay(localDate: LocalDate): LocalDate {
return localDate.plusDays(1)
}
fun getPreviousDay(localDate: LocalDate): LocalDate {
return localDate.minus(1, ChronoUnit.DAYS)
}
fun getDayOfWeek(localDate: LocalDate): DayOfWeek {
return localDate.dayOfWeek
}
fun getFirstDayOfMonth(): LocalDate {
return LocalDate.now().with(TemporalAdjusters.firstDayOfMonth())
}
fun getStartOfDay(localDate: LocalDate): LocalDateTime {
return localDate.atStartOfDay()
}
}
@@ -0,0 +1,10 @@
package com.baeldung.datetime
import java.time.LocalDateTime
class UseLocalDateTime {
fun getLocalDateTimeUsingParseMethod(representation: String): LocalDateTime {
return LocalDateTime.parse(representation)
}
}
@@ -0,0 +1,32 @@
package com.baeldung.datetime
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.temporal.ChronoUnit
class UseLocalTime {
fun getLocalTimeUsingFactoryOfMethod(hour: Int, min: Int, seconds: Int): LocalTime {
return LocalTime.of(hour, min, seconds)
}
fun getLocalTimeUsingParseMethod(timeRepresentation: String): LocalTime {
return LocalTime.parse(timeRepresentation)
}
fun getLocalTimeFromClock(): LocalTime {
return LocalTime.now()
}
fun addAnHour(localTime: LocalTime): LocalTime {
return localTime.plus(1, ChronoUnit.HOURS)
}
fun getHourFromLocalTime(localTime: LocalTime): Int {
return localTime.hour
}
fun getLocalTimeWithMinuteSetToValue(localTime: LocalTime, minute: Int): LocalTime {
return localTime.withMinute(minute)
}
}
@@ -0,0 +1,15 @@
package com.baeldung.datetime
import java.time.LocalDate
import java.time.Period
class UsePeriod {
fun modifyDates(localDate: LocalDate, period: Period): LocalDate {
return localDate.plus(period)
}
fun getDifferenceBetweenDates(localDate1: LocalDate, localDate2: LocalDate): Period {
return Period.between(localDate1, localDate2)
}
}
@@ -0,0 +1,12 @@
package com.baeldung.datetime
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZonedDateTime
class UseZonedDateTime {
fun getZonedDateTime(localDateTime: LocalDateTime, zoneId: ZoneId): ZonedDateTime {
return ZonedDateTime.of(localDateTime, zoneId)
}
}
@@ -0,0 +1,3 @@
package com.baeldung.destructuringdeclarations
data class Person(var id: Int, var name: String, var age: Int)
@@ -0,0 +1,3 @@
package com.baeldung.destructuringdeclarations
data class Result(val result: Int, val status: String)
@@ -0,0 +1,44 @@
package com.baeldung.destructuringdeclarations
import com.baeldung.destructuringdeclarations.Person
fun main(args: Array<String>) {
//2.1. Objects
val person = Person(1, "Jon Snow", 20)
val(id, name, age) = person
println(id) //1
println(name) //Jon Snow
println(age) //20
//2.2. Functions
fun getPersonInfo() = Person(2, "Ned Stark", 45)
val(idf, namef, agef) = getPersonInfo()
fun twoValuesReturn(): Pair<Int, String> {
// needed code
return Pair(1, "success")
}
// Now, to use this function:
val (result, status) = twoValuesReturn()
//2.3. Collections and For-loops
var map: HashMap<Int, Person> = HashMap()
map.put(1, person)
for((key, value) in map){
println("Key: $key, Value: $value")
}
//2.4. Underscore and Destructuring in Lambdas
val (_, name2, age2) = person
val (id3, name3) = person
map.mapValues { entry -> "${entry.value}!" }
map.mapValues { (key, value) -> "$value!" }
}
@@ -0,0 +1,23 @@
package com.baeldung.enums
enum class CardType(val color: String) : ICardLimit {
SILVER("gray") {
override fun getCreditLimit() = 100000
override fun calculateCashbackPercent() = 0.25f
},
GOLD("yellow") {
override fun getCreditLimit() = 200000
override fun calculateCashbackPercent(): Float = 0.5f
},
PLATINUM("black") {
override fun getCreditLimit() = 300000
override fun calculateCashbackPercent() = 0.75f
};
companion object {
fun getCardTypeByColor(color: String) = values().firstOrNull { it.color == color }
fun getCardTypeByName(name: String) = valueOf(name.toUpperCase())
}
abstract fun calculateCashbackPercent(): Float
}
@@ -0,0 +1,5 @@
package com.baeldung.enums
interface ICardLimit {
fun getCreditLimit(): Int
}
@@ -0,0 +1,24 @@
package com.baeldung.filesystem
import java.io.File
class FileReader {
fun readFileLineByLineUsingForEachLine(fileName: String) = File(fileName).forEachLine { println(it) }
fun readFileAsLinesUsingUseLines(fileName: String): List<String> = File(fileName)
.useLines { it.toList() }
fun readFileAsLinesUsingBufferedReader(fileName: String): List<String> = File(fileName).bufferedReader().readLines()
fun readFileAsLinesUsingReadLines(fileName: String): List<String> = File(fileName).readLines()
fun readFileAsTextUsingInputStream(fileName: String) =
File(fileName).inputStream().readBytes().toString(Charsets.UTF_8)
fun readFileDirectlyAsText(fileName: String): String = File(fileName).readText(Charsets.UTF_8)
fun readFileUsingGetResource(fileName: String) = this::class.java.getResource(fileName).readText(Charsets.UTF_8)
fun readFileAsLinesUsingGetResourceAsStream(fileName: String) = this::class.java.getResourceAsStream(fileName).bufferedReader().readLines()
}
@@ -0,0 +1,19 @@
package com.baeldung.filesystem
import java.io.File
class FileWriter {
fun writeFileUsingPrintWriter(fileName: String, fileContent: String) =
File(fileName).printWriter().use { out -> out.print(fileContent) }
fun writeFileUsingBufferedWriter(fileName: String, fileContent: String) =
File(fileName).bufferedWriter().use { out -> out.write(fileContent) }
fun writeFileDirectly(fileName: String, fileContent: String) =
File(fileName).writeText(fileContent)
fun writeFileDirectlyAsBytes(fileName: String, fileContent: String) =
File(fileName).writeBytes(fileContent.toByteArray())
}
@@ -0,0 +1,87 @@
package com.baeldung.forEach
class Country(val name : String, val cities : List<City>)
class City(val name : String, val streets : List<String>)
fun City.getStreetsWithCityName() : List<String> {
return streets.map { "$name, $it" }.toList()
}
fun Country.getCitiesWithCountryName() : List<String> {
return cities.flatMap { it.getStreetsWithCityName() }
.map { "$name, $it" }
}
class World {
private val streetsOfAmsterdam = listOf("Herengracht", "Prinsengracht")
private val streetsOfBerlin = listOf("Unter den Linden","Tiergarten")
private val streetsOfMaastricht = listOf("Grote Gracht", "Vrijthof")
private val countries = listOf(
Country("Netherlands", listOf(City("Maastricht", streetsOfMaastricht),
City("Amsterdam", streetsOfAmsterdam))),
Country("Germany", listOf(City("Berlin", streetsOfBerlin))))
fun allCountriesIt() {
countries.forEach { println(it.name) }
}
fun allCountriesItExplicit() {
countries.forEach { it -> println(it.name) }
}
//here we cannot refer to 'it' anymore inside the forEach
fun allCountriesExplicit() {
countries.forEach { c -> println(c.name) }
}
fun allNested() {
countries.forEach {
println(it.name)
it.cities.forEach {
println(" ${it.name}")
it.streets.forEach { println(" $it") }
}
}
}
fun allTable() {
countries.forEach { c ->
c.cities.forEach { p ->
p.streets.forEach { println("${c.name} ${p.name} $it") }
}
}
}
fun allStreetsFlatMap() {
countries.flatMap { it.cities}
.flatMap { it.streets}
.forEach { println(it) }
}
fun allFlatMapTable() {
countries.flatMap { it.getCitiesWithCountryName() }
.forEach { println(it) }
}
}
fun main(args : Array<String>) {
val world = World()
world.allCountriesExplicit()
world.allNested()
world.allTable()
world.allStreetsFlatMap()
world.allFlatMapTable()
}
@@ -0,0 +1,11 @@
package com.baeldung.fuel
import com.github.kittinunf.fuel.core.Request
fun tokenInterceptor() = {
next: (Request) -> Request ->
{ req: Request ->
req.header(mapOf("Authorization" to "Bearer AbCdEf123456"))
next(req)
}
}
@@ -0,0 +1,15 @@
package com.baeldung.fuel
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.google.gson.Gson
data class Post(var userId:Int,
var id:Int,
var title:String,
var body:String){
class Deserializer : ResponseDeserializable<Array<Post>> {
override fun deserialize(content: String): Array<Post> = Gson().fromJson(content, Array<Post>::class.java)
}
}
@@ -0,0 +1,42 @@
package com.baeldung.fuel
import com.github.kittinunf.fuel.core.Method
import com.github.kittinunf.fuel.util.FuelRouting
sealed class PostRoutingAPI : FuelRouting {
override val basePath = "https://jsonplaceholder.typicode.com"
class posts(val id: String, override val body: String?): PostRoutingAPI()
class comments(val postId: String, override val body: String?): PostRoutingAPI()
override val method: Method
get() {
return when(this) {
is PostRoutingAPI.posts -> Method.GET
is PostRoutingAPI.comments -> Method.GET
}
}
override val path: String
get() {
return when(this) {
is PostRoutingAPI.posts -> "/posts"
is PostRoutingAPI.comments -> "/comments"
}
}
override val params: List<Pair<String, Any?>>?
get() {
return when(this) {
is PostRoutingAPI.posts -> listOf("id" to this.id)
is PostRoutingAPI.comments -> listOf("postId" to this.postId)
}
}
override val headers: Map<String, String>?
get() {
return null
}
}
@@ -0,0 +1,28 @@
package com.baeldung.functions
import kotlin.random.Random
/**
* An extension function on all collections to apply a function to all collection
* elements.
*/
fun <T> Collection<T>.each(block: (T) -> Unit) {
for (e in this) block(e)
}
/**
* In order to see the the JVM bytecode:
* 1. Compile the Kotlin file using `kotlinc Inline.kt`
* 2. Take a peek at the bytecode using the `javap -c InlineKt`
*/
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val random = random()
numbers.each { println(random * it) } // capturing the random variable
}
/**
* Generates a random number.
*/
private fun random(): Int = Random.nextInt()
@@ -0,0 +1,6 @@
inline fun <reified T> Iterable<*>.filterIsInstance() = filter { it is T }
fun main(args: Array<String>) {
val set = setOf("1984", 2, 3, "Brave new world", 11)
println(set.filterIsInstance<Int>())
}
@@ -0,0 +1,60 @@
package com.baeldung.injekt
import org.slf4j.LoggerFactory
import uy.kohesive.injekt.*
import uy.kohesive.injekt.api.*
import java.util.*
class DelegateInjectionApplication {
companion object : InjektMain() {
private val LOG = LoggerFactory.getLogger(DelegateInjectionApplication::class.java)
@JvmStatic fun main(args: Array<String>) {
DelegateInjectionApplication().run()
}
override fun InjektRegistrar.registerInjectables() {
addFactory {
val value = FactoryInstance("Factory" + UUID.randomUUID().toString())
LOG.info("Constructing instance: {}", value)
value
}
addSingletonFactory {
val value = SingletonInstance("Singleton" + UUID.randomUUID().toString())
LOG.info("Constructing singleton instance: {}", value)
value
}
addSingletonFactory { App() }
}
}
data class FactoryInstance(val value: String)
data class SingletonInstance(val value: String)
class App {
private val instance: FactoryInstance by injectValue()
private val lazyInstance: FactoryInstance by injectLazy()
private val singleton: SingletonInstance by injectValue()
private val lazySingleton: SingletonInstance by injectLazy()
fun run() {
for (i in 1..5) {
LOG.info("Instance {}: {}", i, instance)
}
for (i in 1..5) {
LOG.info("Lazy Instance {}: {}", i, lazyInstance)
}
for (i in 1..5) {
LOG.info("Singleton {}: {}", i, singleton)
}
for (i in 1..5) {
LOG.info("Lazy Singleton {}: {}", i, lazySingleton)
}
}
}
fun run() {
Injekt.get<App>().run()
}
}
@@ -0,0 +1,37 @@
package com.baeldung.injekt
import org.slf4j.LoggerFactory
import uy.kohesive.injekt.*
import uy.kohesive.injekt.api.*
class KeyedApplication {
companion object : InjektMain() {
private val LOG = LoggerFactory.getLogger(KeyedApplication::class.java)
@JvmStatic fun main(args: Array<String>) {
KeyedApplication().run()
}
override fun InjektRegistrar.registerInjectables() {
val configs = mapOf(
"google" to Config("googleClientId", "googleClientSecret"),
"twitter" to Config("twitterClientId", "twitterClientSecret")
)
addPerKeyFactory<Config, String> {key -> configs[key]!! }
addSingletonFactory { App() }
}
}
data class Config(val clientId: String, val clientSecret: String)
class App {
fun run() {
LOG.info("Google config: {}", Injekt.get<Config>("google"))
LOG.info("Twitter config: {}", Injekt.get<Config>("twitter"))
}
}
fun run() {
Injekt.get<App>().run()
}
}
@@ -0,0 +1,46 @@
package com.baeldung.injekt
import org.slf4j.LoggerFactory
import uy.kohesive.injekt.*
import uy.kohesive.injekt.api.*
class ModularApplication {
class ConfigModule(private val port: Int) : InjektModule {
override fun InjektRegistrar.registerInjectables() {
addSingleton(Config(port))
}
}
object ServerModule : InjektModule {
override fun InjektRegistrar.registerInjectables() {
addSingletonFactory { Server(Injekt.get()) }
}
}
companion object : InjektMain() {
private val LOG = LoggerFactory.getLogger(Server::class.java)
@JvmStatic fun main(args: Array<String>) {
ModularApplication().run()
}
override fun InjektRegistrar.registerInjectables() {
importModule(ConfigModule(12345))
importModule(ServerModule)
}
}
data class Config(
val port: Int
)
class Server(private val config: Config) {
fun start() {
LOG.info("Starting server on ${config.port}")
}
}
fun run() {
Injekt.get<Server>().start()
}
}
@@ -0,0 +1,48 @@
package com.baeldung.injekt
import org.slf4j.LoggerFactory
import uy.kohesive.injekt.*
import uy.kohesive.injekt.api.*
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class PerThreadApplication {
companion object : InjektMain() {
private val LOG = LoggerFactory.getLogger(PerThreadApplication::class.java)
@JvmStatic fun main(args: Array<String>) {
PerThreadApplication().run()
}
override fun InjektRegistrar.registerInjectables() {
addPerThreadFactory {
val value = FactoryInstance(UUID.randomUUID().toString())
LOG.info("Constructing instance: {}", value)
value
}
addSingletonFactory { App() }
}
}
data class FactoryInstance(val value: String)
class App {
fun run() {
val threadPool = Executors.newFixedThreadPool(5)
for (i in 1..20) {
threadPool.submit {
val instance = Injekt.get<FactoryInstance>()
LOG.info("Value for thread {}: {}", Thread.currentThread().id, instance)
TimeUnit.MILLISECONDS.sleep(100)
}
}
threadPool.awaitTermination(10, TimeUnit.SECONDS)
}
}
fun run() {
Injekt.get<App>().run()
}
}
@@ -0,0 +1,34 @@
package com.baeldung.injekt
import org.slf4j.LoggerFactory
import uy.kohesive.injekt.*
import uy.kohesive.injekt.api.*
class SimpleApplication {
companion object : InjektMain() {
private val LOG = LoggerFactory.getLogger(Server::class.java)
@JvmStatic fun main(args: Array<String>) {
SimpleApplication().run()
}
override fun InjektRegistrar.registerInjectables() {
addSingleton(Config(12345))
addSingletonFactory { Server(Injekt.get()) }
}
}
data class Config(
val port: Int
)
class Server(private val config: Config) {
fun start() {
LOG.info("Starting server on ${config.port}")
}
}
fun run() {
Injekt.get<Server>().start()
}
}
@@ -0,0 +1,14 @@
package com.baeldung.inline.classes
interface Drawable {
fun draw()
}
inline class CircleRadius(private val circleRadius : Double) : Drawable {
val diameterOfCircle get() = 2 * circleRadius
fun areaOfCircle() = 3.14 * circleRadius * circleRadius
override fun draw() {
println("Draw my circle")
}
}
@@ -0,0 +1,3 @@
package com.baeldung.inline.classes
inline class InlineDoubleWrapper(val doubleValue : Double)
@@ -0,0 +1,23 @@
package com.baeldung.interfaces
interface BaseInterface {
fun someMethod(): String
}
interface FirstChildInterface : BaseInterface {
override fun someMethod(): String {
return("Hello, from someMethod in FirstChildInterface")
}
}
interface SecondChildInterface : BaseInterface {
override fun someMethod(): String {
return("Hello, from someMethod in SecondChildInterface")
}
}
class ChildClass : FirstChildInterface, SecondChildInterface {
override fun someMethod(): String {
return super<SecondChildInterface>.someMethod()
}
}
@@ -0,0 +1,13 @@
package com.baeldung.interfaces
interface MyInterface {
fun someMethod(): String
}
class MyClass() : MyInterface {
override fun someMethod(): String {
return("Hello, World!")
}
}
class MyDerivedClass(myInterface: MyInterface) : MyInterface by myInterface
@@ -0,0 +1,29 @@
package com.baeldung.interfaces
interface FirstInterface {
fun someMethod(): String
fun anotherMethod(): String {
return("Hello, from anotherMethod in FirstInterface")
}
}
interface SecondInterface {
fun someMethod(): String {
return("Hello, from someMethod in SecondInterface")
}
fun anotherMethod(): String {
return("Hello, from anotherMethod in SecondInterface")
}
}
class SomeClass: FirstInterface, SecondInterface {
override fun someMethod(): String {
return("Hello, from someMethod in SomeClass")
}
override fun anotherMethod(): String {
return("Hello, from anotherMethod in SomeClass")
}
}
@@ -0,0 +1,24 @@
package com.baeldung.interfaces
interface SimpleInterface {
val firstProp: String
val secondProp: String
get() = "Second Property"
fun firstMethod(): String
fun secondMethod(): String {
println("Hello, from: " + secondProp)
return ""
}
}
class SimpleClass: SimpleInterface {
override val firstProp: String = "First Property"
override val secondProp: String
get() = "Second Property, Overridden!"
override fun firstMethod(): String {
return("Hello, from: " + firstProp)
}
override fun secondMethod(): String {
return("Hello, from: " + secondProp + firstProp)
}
}
@@ -0,0 +1,5 @@
package com.baeldung.kotlin
fun main(args: Array<String>){
println("hello word")
}
@@ -0,0 +1,14 @@
package com.baeldung.kotlin
open class Item(val id: String, val name: String = "unknown_name") {
open fun getIdOfItem(): String {
return id
}
}
class ItemWithCategory(id: String, name: String, val categoryId: String) : Item(id, name) {
override fun getIdOfItem(): String {
return id + name
}
}
@@ -0,0 +1,83 @@
package com.baeldung.kotlin
import java.util.*
class ItemService {
fun findItemNameForId(id: String): Item? {
val itemId = UUID.randomUUID().toString()
return Item(itemId, "name-$itemId")
}
}
class ItemManager(val categoryId: String, val dbConnection: String) {
var email = ""
constructor(categoryId: String, dbConnection: String, email: String)
: this(categoryId, dbConnection) {
this.email = email
}
fun isFromSpecificCategory(catId: String): Boolean {
return categoryId == catId
}
fun makeAnalyisOfCategory(catId: String): Unit {
val result = if (catId == "100") "Yes" else "No"
println(result)
`object`()
}
fun sum(a: Int, b: Int): Int {
return a + b
}
fun `object`(): String {
return "this is object"
}
}
fun main(args: Array<String>) {
val numbers = arrayOf("first", "second", "third", "fourth")
for (n in numbers) {
println(n)
}
for (i in 2..9 step 2) {
println(i)
}
val res = 1.rangeTo(10).map { it * 2 }
println(res)
val firstName = "Tom"
val secondName = "Mary"
val concatOfNames = "$firstName + $secondName"
println("Names: $concatOfNames")
val sum = "four: ${2 + 2}"
val itemManager = ItemManager("cat_id", "db://connection")
ItemManager(categoryId = "catId", dbConnection = "db://Connection")
val result = "function result: ${itemManager.isFromSpecificCategory("1")}"
println(result)
val number = 2
if (number < 10) {
println("number less that 10")
} else if (number > 10) {
println("number is greater that 10")
}
val name = "John"
when (name) {
"John" -> println("Hi man")
"Alice" -> println("Hi lady")
}
val items = listOf(1, 2, 3, 4)
val rwList = mutableListOf(1, 2, 3)
rwList.add(5)
}
@@ -0,0 +1,12 @@
package com.baeldung.kotlin
class JvmSample(text:String) {
@JvmField
val sampleText:String = text
}
class CompanionSample {
companion object {
@JvmField val MAX_LIMIT = 20
}
}
@@ -0,0 +1,14 @@
package com.baeldung.kotlin
import java.util.concurrent.ThreadLocalRandom
class ListExtension {
fun <T> List<T>.random(): T? {
if (this.isEmpty()) return null
return get(ThreadLocalRandom.current().nextInt(count()))
}
fun <T> getRandomElementOfList(list: List<T>): T? {
return list.random()
}
}
@@ -0,0 +1,7 @@
package com.baeldung.kotlin
class MathematicsOperations {
fun addTwoNumbers(a: Int, b: Int): Int {
return a + b
}
}
@@ -0,0 +1,19 @@
package com.baeldung.kotlin
sealed class Result<out S, out F> {
abstract fun <R> map(func: (S) -> R) : Result<R, F>
abstract fun <R> mapFailure(func: (F) -> R) : Result<S, R>
abstract fun get() : S?
}
data class Success<out S, out F>(val success: S) : Result<S, F>() {
override fun <R> map(func: (S) -> R) : Result<R, F> = Success(func(success))
override fun <R> mapFailure(func: (F) -> R): Result<S, R> = Success(success)
override fun get(): S? = success
}
data class Failure<out S, out F>(val failure: F) : Result<S, F>() {
override fun <R> map(func: (S) -> R) : Result<R, F> = Failure(failure)
override fun <R> mapFailure(func: (F) -> R): Result<S, R> = Failure(func(failure))
override fun get(): S? = null
}
@@ -0,0 +1,9 @@
@file:JvmName("Strings")
package com.baeldung.kotlin
fun String.escapeForXml() : String {
return this
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
}
@@ -0,0 +1,3 @@
package com.baeldung.kotlin
data class User(val name: String, val age: Int, val hobbies: List<String>)
@@ -0,0 +1,28 @@
package com.baeldung.kotlin
enum class UnixFileType {
D, HYPHEN_MINUS, L
}
sealed class UnixFile {
abstract fun getFileType(): UnixFileType
class RegularFile(val content: String) : UnixFile() {
override fun getFileType(): UnixFileType {
return UnixFileType.HYPHEN_MINUS
}
}
class Directory(val children: List<UnixFile>) : UnixFile() {
override fun getFileType(): UnixFileType {
return UnixFileType.D
}
}
class SymbolicLink(val originalFile: UnixFile) : UnixFile() {
override fun getFileType(): UnixFileType {
return UnixFileType.L
}
}
}
@@ -0,0 +1,35 @@
package com.baeldung.kotlin.delegates
val data = arrayOf<MutableMap<String, Any?>>(
mutableMapOf(
"id" to 1,
"name" to "George",
"age" to 4
),
mutableMapOf(
"id" to 2,
"name" to "Charlotte",
"age" to 2
)
)
class NoRecordFoundException(id: Int) : Exception("No record found for id $id") {
init {
println("No record found for ID $id")
}
}
fun queryForValue(field: String, id: Int): Any {
println("Loading record $id from the fake database")
val value = data.firstOrNull { it["id"] == id }
?.get(field) ?: throw NoRecordFoundException(id)
println("Loaded value $value for field $field of record $id")
return value
}
fun update(field: String, id: Int, value: Any?) {
println("Updating field $field of record $id to value $value in the fake database")
data.firstOrNull { it["id"] == id }
?.put(field, value)
?: throw NoRecordFoundException(id)
}
@@ -0,0 +1,13 @@
package com.baeldung.kotlin.delegates
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class DatabaseDelegate<in R, T>(private val field: String, private val id: Int) : ReadWriteProperty<R, T> {
override fun getValue(thisRef: R, property: KProperty<*>): T =
queryForValue(field, id) as T
override fun setValue(thisRef: R, property: KProperty<*>, value: T) {
update(field, id, value)
}
}
@@ -0,0 +1,64 @@
package com.baeldung.kotlin.delegates
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
interface Producer {
fun produce(): String
}
class ProducerImpl : Producer {
override fun produce() = "ProducerImpl"
}
class EnhancedProducer(private val delegate: Producer) : Producer by delegate {
override fun produce() = "${delegate.produce()} and EnhancedProducer"
}
interface MessageService {
fun processMessage(message: String): String
}
class MessageServiceImpl : MessageService {
override fun processMessage(message: String): String {
return "MessageServiceImpl: $message"
}
}
interface UserService {
fun processUser(userId: String): String
}
class UserServiceImpl : UserService {
override fun processUser(userId: String): String {
return "UserServiceImpl: $userId"
}
}
class CompositeService : UserService by UserServiceImpl(), MessageService by MessageServiceImpl()
interface Service {
val seed: Int
fun serve(action: (Int) -> Unit)
}
class ServiceImpl : Service {
override val seed = 1
override fun serve(action: (Int) -> Unit) {
action(seed)
}
}
class ServiceDecorator : Service by ServiceImpl() {
override val seed = 2
}
@@ -0,0 +1,6 @@
package com.baeldung.kotlin.delegates
class User(val id: Int) {
var name: String by DatabaseDelegate("name", id)
var age: Int by DatabaseDelegate("age", id)
}
@@ -0,0 +1,114 @@
package com.baeldung.kotlin.dsl
abstract class Condition {
fun and(initializer: Condition.() -> Unit) {
addCondition(And().apply(initializer))
}
fun or(initializer: Condition.() -> Unit) {
addCondition(Or().apply(initializer))
}
infix fun String.eq(value: Any?) {
addCondition(Eq(this, value))
}
protected abstract fun addCondition(condition: Condition)
}
open class CompositeCondition(private val sqlOperator: String) : Condition() {
private val conditions = mutableListOf<Condition>()
override fun addCondition(condition: Condition) {
conditions += condition
}
override fun toString(): String {
return if (conditions.size == 1) {
conditions.first().toString()
} else {
conditions.joinToString(prefix = "(", postfix = ")", separator = " $sqlOperator ") {
"$it"
}
}
}
}
class And : CompositeCondition("and")
class Or : CompositeCondition("or")
class Eq(private val column: String, private val value: Any?) : Condition() {
init {
if (value != null && value !is Number && value !is String) {
throw IllegalArgumentException("Only <null>, numbers and strings values can be used in the 'where' clause")
}
}
override fun addCondition(condition: Condition) {
throw IllegalStateException("Can't add a nested condition to the sql 'eq'")
}
override fun toString(): String {
return when (value) {
null -> "$column is null"
is String -> "$column = '$value'"
else -> "$column = $value"
}
}
}
class SqlSelectBuilder {
private val columns = mutableListOf<String>()
private lateinit var table: String
private var condition: Condition? = null
fun select(vararg columns: String) {
if (columns.isEmpty()) {
throw IllegalArgumentException("At least one column should be defined")
}
if (this.columns.isNotEmpty()) {
throw IllegalStateException("Detected an attempt to re-define columns to fetch. Current columns list: "
+ "${this.columns}, new columns list: $columns")
}
this.columns.addAll(columns)
}
fun from(table: String) {
this.table = table
}
fun where(initializer: Condition.() -> Unit) {
condition = And().apply(initializer)
}
fun build(): String {
if (!::table.isInitialized) {
throw IllegalStateException("Failed to build an sql select - target table is undefined")
}
return toString()
}
override fun toString(): String {
val columnsToFetch =
if (columns.isEmpty()) {
"*"
} else {
columns.joinToString(", ")
}
val conditionString =
if (condition == null) {
""
} else {
" where $condition"
}
return "select $columnsToFetch from $table$conditionString"
}
}
fun query(initializer: SqlSelectBuilder.() -> Unit): SqlSelectBuilder {
return SqlSelectBuilder().apply(initializer)
}
@@ -0,0 +1,30 @@
package com.baeldung.kotlin.logging
import org.slf4j.Logger
open class LoggerAsExtensionOnAny {
val logger = logger()
fun log(s: String) {
logger().info(s)
logger.info(s)
}
}
class ExtensionSubclass : LoggerAsExtensionOnAny()
fun <T : Any> T.logger(): Logger = getLogger(getClassForLogging(javaClass))
fun main(args: Array<String>) {
LoggerAsExtensionOnAny().log("test")
ExtensionSubclass().log("sub")
"foo".logger().info("foo")
1.logger().info("uh-oh!")
SomeOtherClass().logger()
}
class SomeOtherClass {
fun logger(): String {
return "foo"
}
}
@@ -0,0 +1,30 @@
package com.baeldung.kotlin.logging
import org.slf4j.Logger
import org.slf4j.LoggerFactory
interface Logging
inline fun <reified T : Logging> T.logger(): Logger =
//Wrong logger name!
//LoggerFactory.getLogger(javaClass.name + " w/interface")
LoggerFactory.getLogger(getClassForLogging(T::class.java).name + " w/interface")
open class LoggerAsExtensionOnMarkerInterface : Logging {
companion object : Logging {
val logger = logger()
}
fun log(s: String) {
logger().info(s)
logger.info(s)
}
}
class MarkerExtensionSubclass : LoggerAsExtensionOnMarkerInterface()
fun main(args: Array<String>) {
LoggerAsExtensionOnMarkerInterface().log("test")
MarkerExtensionSubclass().log("sub")
"foo".logger().info("foo")
}
@@ -0,0 +1,17 @@
package com.baeldung.kotlin.logging
open class LoggerAsProperty {
private val logger = getLogger(javaClass)
fun log(s: String) {
logger.info(s)
}
}
class PropertySubclass : LoggerAsProperty()
fun main(args: Array<String>) {
LoggerAsProperty().log("test")
PropertySubclass().log("sub")
}
@@ -0,0 +1,47 @@
package com.baeldung.kotlin.logging
import org.slf4j.Logger
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
open class LoggerAsPropertyDelegate {
private val lazyLogger by lazyLogger()
protected val logger by LoggerDelegate()
private val logger2 = logger
companion object {
private val lazyLoggerComp by lazyLogger()
private val loggerComp by LoggerDelegate()
}
open fun log(s: String) {
logger.info(s)
logger2.info(s)
lazyLogger.info(s)
loggerComp.info(s)
lazyLoggerComp.info(s)
}
}
class DelegateSubclass : LoggerAsPropertyDelegate() {
override fun log(s: String) {
logger.info("-- in sub")
super.log(s)
}
}
fun lazyLogger(forClass: Class<*>): Lazy<Logger> =
lazy { getLogger(getClassForLogging(forClass)) }
fun <T : Any> T.lazyLogger(): Lazy<Logger> = lazyLogger(javaClass)
fun main(args: Array<String>) {
LoggerAsPropertyDelegate().log("test")
DelegateSubclass().log("sub")
}
class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> {
override fun getValue(thisRef: R, property: KProperty<*>) =
getLogger(getClassForLogging(thisRef.javaClass))
}
@@ -0,0 +1,44 @@
package com.baeldung.kotlin.logging
open class LoggerInCompanionObject {
companion object {
private val loggerWithExplicitClass = getLogger(LoggerInCompanionObject::class.java)
@Suppress("JAVA_CLASS_ON_COMPANION")
private val loggerWithWrongClass = getLogger(javaClass)
@Suppress("JAVA_CLASS_ON_COMPANION")
private val logger = getLogger(javaClass.enclosingClass)
}
fun log(s: String) {
loggerWithExplicitClass.info(s)
loggerWithWrongClass.info(s)
logger.info(s)
}
class Inner {
companion object {
private val loggerWithExplicitClass = getLogger(Inner::class.java)
@Suppress("JAVA_CLASS_ON_COMPANION")
@JvmStatic
private val loggerWithWrongClass = getLogger(javaClass)
@Suppress("JAVA_CLASS_ON_COMPANION")
@JvmStatic
private val logger = getLogger(javaClass.enclosingClass)
}
fun log(s: String) {
loggerWithExplicitClass.info(s)
loggerWithWrongClass.info(s)
logger.info(s)
}
}
}
class CompanionSubclass : LoggerInCompanionObject()
fun main(args: Array<String>) {
LoggerInCompanionObject().log("test")
LoggerInCompanionObject.Inner().log("test")
CompanionSubclass().log("sub")
}
@@ -0,0 +1,13 @@
package com.baeldung.kotlin.logging
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.reflect.full.companionObject
fun getLogger(forClass: Class<*>): Logger = LoggerFactory.getLogger(forClass)
fun <T : Any> getClassForLogging(javaClass: Class<T>): Class<*> {
return javaClass.enclosingClass?.takeIf {
it.kotlin.companionObject?.java == javaClass
} ?: javaClass
}
@@ -0,0 +1,84 @@
package com.baeldung.lambda
fun inferredType(input: Int): Int {
val square = { number: Int -> number * number }
return square(input)
}
fun intToBiggerString(argument: Int): String {
val magnitude100String = { input: Int ->
val magnitude = input * 100
magnitude.toString()
}
return magnitude100String(argument)
}
fun manyLambda(nums: Array<Int>): List<String> {
val newList = nums.map { intToBiggerString(it) }
return newList
}
fun empty() {
val noReturn: (Int) -> Unit = { num -> println(num) }
noReturn(5)
}
fun invokeLambda(lambda: (Double) -> Boolean): Boolean {
return lambda(4.329)
}
fun extendString(arg: String, num: Int): String {
val another: String.(Int) -> String = { this + it }
return arg.another(num)
}
fun getCalculationLambda(): (Int) -> Any {
val calculateGrade = { grade: Int ->
when (grade) {
in 0..40 -> "Fail"
in 41..70 -> "Pass"
in 71..100 -> "Distinction"
else -> false
}
}
return calculateGrade
}
fun getCalculationLambdaWithReturn(): (Int) -> String {
val calculateGrade: Int.() -> String = lambda@{
if (this < 0 || this > 100) {
return@lambda "Error"
} else if (this < 40) {
return@lambda "Fail"
} else if (this < 70) {
return@lambda "Pass"
}
"Distinction"
}
return calculateGrade
}
fun getCalculationAnonymousFunction(): (Int) -> String {
val calculateGrade = fun(grade: Int): String {
if (grade < 0 || grade > 100) {
return "Error"
} else if (grade < 40) {
return "Fail"
} else if (grade < 70) {
return "Pass"
}
return "Distinction"
}
return calculateGrade
}
@@ -0,0 +1,9 @@
package com.baeldung.mavenjavakotlin.services
class KotlinService {
fun sayHello() {
System.out.println("Kotlin says 'Hello World!'")
}
}
@@ -0,0 +1,75 @@
package com.baeldung.nested
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class Computer(val model: String) {
companion object {
const val originCountry = "China"
fun getBuiltDate(): String {
return "2018-05-23"
}
val log: Logger = LoggerFactory.getLogger(Computer::class.java)
}
//Nested class
class MotherBoard(val manufacturer: String) {
fun getInfo() = "Made by $manufacturer installed in $originCountry - ${getBuiltDate()}"
}
//Inner class
inner class HardDisk(val sizeInGb: Int) {
fun getInfo() = "Installed on ${this@Computer} with $sizeInGb GB"
}
interface Switcher {
fun on(): String
}
interface Protector {
fun smart()
}
fun powerOn(): String {
//Local class
var defaultColor = "Blue"
class Led(val color: String) {
fun blink(): String {
return "blinking $color"
}
fun changeDefaultPowerOnColor() {
defaultColor = "Violet"
}
}
val powerLed = Led("Green")
log.debug("defaultColor is $defaultColor")
powerLed.changeDefaultPowerOnColor()
log.debug("defaultColor changed inside Led class to $defaultColor")
//Anonymous object
val powerSwitch = object : Switcher, Protector {
override fun on(): String {
return powerLed.blink()
}
override fun smart() {
log.debug("Smart protection is implemented")
}
fun changeDefaultPowerOnColor() {
defaultColor = "Yellow"
}
}
powerSwitch.changeDefaultPowerOnColor()
log.debug("defaultColor changed inside powerSwitch anonymous object to $defaultColor")
return powerSwitch.on()
}
override fun toString(): String {
return "Computer(model=$model)"
}
}
@@ -0,0 +1,31 @@
package com.baeldung.operators
import java.math.BigDecimal
enum class Currency {
DOLLARS, EURO
}
class Money(val amount: BigDecimal, val currency: Currency) : Comparable<Money> {
override fun compareTo(other: Money): Int =
convert(Currency.DOLLARS).compareTo(other.convert(Currency.DOLLARS))
fun convert(currency: Currency): BigDecimal = TODO()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Money) return false
if (amount != other.amount) return false
if (currency != other.currency) return false
return true
}
override fun hashCode(): Int {
var result = amount.hashCode()
result = 31 * result + currency.hashCode()
return result
}
}
@@ -0,0 +1,16 @@
package com.baeldung.operators
interface Page<T> {
fun pageNumber(): Int
fun pageSize(): Int
fun elements(): MutableList<T>
}
operator fun <T> Page<T>.get(index: Int): T = elements()[index]
operator fun <T> Page<T>.get(start: Int, endExclusive: Int): List<T> = elements().subList(start, endExclusive)
operator fun <T> Page<T>.set(index: Int, value: T) {
elements()[index] = value
}
operator fun <T> Page<T>.contains(element: T): Boolean = element in elements()
operator fun <T> Page<T>.iterator() = elements().iterator()
@@ -0,0 +1,31 @@
package com.baeldung.operators
data class Point(val x: Int, val y: Int)
operator fun Point.unaryMinus() = Point(-x, -y)
operator fun Point.not() = Point(y, x)
operator fun Point.inc() = Point(x + 1, y + 1)
operator fun Point.dec() = Point(x - 1, y - 1)
operator fun Point.plus(other: Point): Point = Point(x + other.x, y + other.y)
operator fun Point.minus(other: Point): Point = Point(x - other.x, y - other.y)
operator fun Point.times(other: Point): Point = Point(x * other.x, y * other.y)
operator fun Point.div(other: Point): Point = Point(x / other.x, y / other.y)
operator fun Point.rem(other: Point): Point = Point(x % other.x, y % other.y)
operator fun Point.times(factor: Int): Point = Point(x * factor, y * factor)
operator fun Int.times(point: Point): Point = Point(point.x * this, point.y * this)
class Shape {
val points = mutableListOf<Point>()
operator fun Point.unaryPlus() {
points.add(this)
}
}
fun shape(init: Shape.() -> Unit): Shape {
val shape = Shape()
shape.init()
return shape
}
@@ -0,0 +1,8 @@
package com.baeldung.operators
import java.math.BigInteger
operator fun <T> MutableCollection<T>.plusAssign(element: T) {
add(element)
}
operator fun BigInteger.plus(other: Int): BigInteger = add(BigInteger("$other"))
@@ -0,0 +1,44 @@
package com.baeldung.sorting
import kotlin.comparisons.*
fun sortMethodUsage() {
val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6)
sortedValues.sort()
println(sortedValues)
}
fun sortByMethodUsage() {
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
sortedValues.sortBy { it.second }
println(sortedValues)
}
fun sortWithMethodUsage() {
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
sortedValues.sortWith(compareBy({it.second}, {it.first}))
println(sortedValues)
}
fun <T : kotlin.Comparable<T>> getSimpleComparator() : Comparator<T> {
val ascComparator = naturalOrder<T>()
return ascComparator
}
fun getComplexComparator() {
val complexComparator = compareBy<Pair<Int, String>>({it.first}, {it.second})
}
fun nullHandlingUsage() {
val sortedValues = mutableListOf(1 to "a", 2 to null, 7 to "c", 6 to "d", 5 to "c", 6 to "e")
sortedValues.sortWith(nullsLast(compareBy { it.second }))
println(sortedValues)
}
fun extendedComparatorUsage() {
val students = mutableListOf(21 to "Helen", 21 to "Tom", 20 to "Jim")
val ageComparator = compareBy<Pair<Int, String?>> {it.first}
val ageAndNameComparator = ageComparator.thenByDescending {it.second}
println(students.sortedWith(ageAndNameComparator))
}
@@ -0,0 +1,10 @@
package com.baeldung.static
class ConsoleUtils {
companion object {
@JvmStatic
fun debug(debugMessage : String) {
println("[DEBUG] $debugMessage")
}
}
}
@@ -0,0 +1,5 @@
package com.baeldung.static
fun debug(debugMessage : String) {
println("[DEBUG] $debugMessage")
}
@@ -0,0 +1,115 @@
package com.baeldung.stringtemplates
/**
* Example of a useful function defined in Kotlin String class
*/
fun padExample(): String {
return "Hello".padEnd(10, '!')
}
/**
* Example of a simple string template usage
*/
fun simpleTemplate(n: Int): String {
val message = "n = $n"
return message
}
/**
* Example of a string template with a simple expression
*/
fun templateWithExpression(n: Int): String {
val message = "n + 1 = ${n + 1}"
return message
}
/**
* Example of a string template with expression containing some logic
*/
fun templateWithLogic(n: Int): String {
val message = "$n is ${if (n > 0) "positive" else "not positive"}"
return message
}
/**
* Example of nested string templates
*/
fun nestedTemplates(n: Int): String {
val message = "$n is ${if (n > 0) "positive" else if (n < 0) "negative and ${if (n % 2 == 0) "even" else "odd"}" else "zero"}"
return message
}
/**
* Example of joining array's element into a string with a default separator
*/
fun templateJoinArray(): String {
val numbers = listOf(1, 1, 2, 3, 5, 8)
val message = "first Fibonacci numbers: ${numbers.joinToString()}"
return message
}
/**
* Example of escaping the dollar sign
*/
fun notAStringTemplate(): String {
val message = "n = \$n"
return message
}
/**
* Example of a simple triple quoted string
*/
fun showFilePath(): String {
val path = """C:\Repository\read.me"""
return path
}
/**
* Example of a multiline string
*/
fun showMultiline(): String {
val receipt = """Item 1: $1.00
Item 2: $0.50"""
return receipt
}
/**
* Example of a multiline string with indentation
*/
fun showMultilineIndent(): String {
val receipt = """Item 1: $1.00
>Item 2: $0.50""".trimMargin(">")
return receipt
}
/**
* Example of a triple quoted string with a not-working escape sequence
*/
fun showTripleQuotedWrongEscape(): String {
val receipt = """Item 1: $1.00\nItem 2: $0.50"""
return receipt
}
/**
* Example of a triple quoted string with a correctly working escape sequence
*/
fun showTripleQuotedCorrectEscape(): String {
val receipt = """Item 1: $1.00${"\n"}Item 2: $0.50"""
return receipt
}
fun main(args: Array<String>) {
println(padExample())
println(simpleTemplate(10))
println(templateWithExpression(5))
println(templateWithLogic(7))
println(nestedTemplates(-5))
println(templateJoinArray())
println(notAStringTemplate())
println(showFilePath())
println(showMultiline())
println(showMultilineIndent())
println(showTripleQuotedWrongEscape())
println(showTripleQuotedCorrectEscape())
}
@@ -0,0 +1,8 @@
package com.baeldung.thread
class SimpleRunnable: Runnable {
override fun run() {
println("${Thread.currentThread()} has run.")
}
}
@@ -0,0 +1,8 @@
package com.baeldung.thread
class SimpleThread: Thread() {
override fun run() {
println("${Thread.currentThread()} has run.")
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,17 @@
package com.baeldung.kotlin;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class JavaCallToKotlinUnitTest {
@Test
public void givenKotlinClass_whenCallFromJava_shouldProduceResults() {
//when
int res = new MathematicsOperations().addTwoNumbers(2, 4);
//then
assertEquals(6, res);
}
}

Some files were not shown because too many files have changed in this diff Show More