[BAEL-19885] - Move articles out of core-kotlin part4
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
## Core Kotlin Advanced
|
||||
|
||||
This module contains articles about advanced topics in Kotlin.
|
||||
|
||||
### Relevant articles:
|
||||
- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl)
|
||||
- [Regular Expressions in Kotlin](https://www.baeldung.com/kotlin-regular-expressions)
|
||||
- [Idiomatic Logging in Kotlin](https://www.baeldung.com/kotlin-logging)
|
||||
- [Mapping of Data Objects in Kotlin](https://www.baeldung.com/kotlin-data-objects)
|
||||
- [Reflection with Kotlin](https://www.baeldung.com/kotlin-reflection)
|
||||
- [Kotlin Contracts](https://www.baeldung.com/kotlin-contracts)
|
||||
@@ -0,0 +1,41 @@
|
||||
<?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-advanced</artifactId>
|
||||
<name>core-kotlin-advanced</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
||||
<artifactId>core-kotlin-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-test</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<kotlin.version>1.3.30</kotlin.version>
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+23
@@ -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
|
||||
}
|
||||
|
||||
+43
@@ -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
|
||||
}
|
||||
+10
@@ -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)
|
||||
+22
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
+8
@@ -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,114 @@
|
||||
package com.baeldung.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)
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.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"
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.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")
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.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")
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.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))
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.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.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
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.datamapping
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.assertAll
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class UserTest {
|
||||
|
||||
@Test
|
||||
fun `maps User to UserResponse using extension function`() {
|
||||
val p = buildUser()
|
||||
val view = p.toUserView()
|
||||
assertUserView(view)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `maps User to UserResponse using reflection`() {
|
||||
val p = buildUser()
|
||||
val view = p.toUserViewReflection()
|
||||
assertUserView(view)
|
||||
}
|
||||
|
||||
private fun buildUser(): User {
|
||||
return User(
|
||||
"Java",
|
||||
"Duke",
|
||||
"Javastreet",
|
||||
"42",
|
||||
"1234567",
|
||||
30,
|
||||
"s3cr37"
|
||||
)
|
||||
}
|
||||
|
||||
private fun assertUserView(pr: UserView) {
|
||||
assertAll(
|
||||
{ assertEquals("Java Duke", pr.name) },
|
||||
{ assertEquals("Javastreet 42", pr.address) },
|
||||
{ assertEquals("1234567", pr.telephone) },
|
||||
{ assertEquals(30, pr.age) }
|
||||
)
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.dsl
|
||||
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.Test
|
||||
|
||||
class SqlDslTest {
|
||||
|
||||
@Test
|
||||
fun `when no columns are specified then star is used`() {
|
||||
doTest("select * from table1") {
|
||||
from ("table1")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `when no condition is specified then correct query is built`() {
|
||||
doTest("select column1, column2 from table1") {
|
||||
select("column1", "column2")
|
||||
from ("table1")
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = Exception::class)
|
||||
fun `when no table is specified then an exception is thrown`() {
|
||||
query {
|
||||
select("column1")
|
||||
}.build()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `when a list of conditions is specified then it's respected`() {
|
||||
doTest("select * from table1 where (column3 = 4 and column4 is null)") {
|
||||
from ("table1")
|
||||
where {
|
||||
"column3" eq 4
|
||||
"column4" eq null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `when 'or' conditions are specified then they are respected`() {
|
||||
doTest("select * from table1 where (column3 = 4 or column4 is null)") {
|
||||
from ("table1")
|
||||
where {
|
||||
or {
|
||||
"column3" eq 4
|
||||
"column4" eq null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `when either 'and' or 'or' conditions are specified then they are respected`() {
|
||||
doTest("select * from table1 where ((column3 = 4 or column4 is null) and column5 = 42)") {
|
||||
from ("table1")
|
||||
where {
|
||||
and {
|
||||
or {
|
||||
"column3" eq 4
|
||||
"column4" eq null
|
||||
}
|
||||
"column5" eq 42
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun doTest(expected: String, sql: SqlSelectBuilder.() -> Unit) {
|
||||
assertThat(query(sql).build()).isEqualTo(expected)
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.reflection
|
||||
|
||||
import org.junit.Ignore
|
||||
import org.junit.Test
|
||||
import org.slf4j.LoggerFactory
|
||||
|
||||
@Ignore
|
||||
class JavaReflectionTest {
|
||||
private val LOG = LoggerFactory.getLogger(KClassTest::class.java)
|
||||
|
||||
@Test
|
||||
fun listJavaClassMethods() {
|
||||
Exception::class.java.methods
|
||||
.forEach { method -> LOG.info("Method: {}", method) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listKotlinClassMethods() {
|
||||
JavaReflectionTest::class.java.methods
|
||||
.forEach { method -> LOG.info("Method: {}", method) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listKotlinDataClassMethods() {
|
||||
data class ExampleDataClass(val name: String, var enabled: Boolean)
|
||||
|
||||
ExampleDataClass::class.java.methods
|
||||
.forEach { method -> LOG.info("Method: {}", method) }
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.reflection
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Ignore
|
||||
import org.junit.Test
|
||||
import org.slf4j.LoggerFactory
|
||||
import java.math.BigDecimal
|
||||
import kotlin.reflect.full.*
|
||||
|
||||
class KClassTest {
|
||||
private val LOG = LoggerFactory.getLogger(KClassTest::class.java)
|
||||
|
||||
@Test
|
||||
fun testKClassDetails() {
|
||||
val stringClass = String::class
|
||||
Assert.assertEquals("kotlin.String", stringClass.qualifiedName)
|
||||
Assert.assertFalse(stringClass.isData)
|
||||
Assert.assertFalse(stringClass.isCompanion)
|
||||
Assert.assertFalse(stringClass.isAbstract)
|
||||
Assert.assertTrue(stringClass.isFinal)
|
||||
Assert.assertFalse(stringClass.isSealed)
|
||||
|
||||
val listClass = List::class
|
||||
Assert.assertEquals("kotlin.collections.List", listClass.qualifiedName)
|
||||
Assert.assertFalse(listClass.isData)
|
||||
Assert.assertFalse(listClass.isCompanion)
|
||||
Assert.assertTrue(listClass.isAbstract)
|
||||
Assert.assertFalse(listClass.isFinal)
|
||||
Assert.assertFalse(listClass.isSealed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetRelated() {
|
||||
LOG.info("Companion Object: {}", TestSubject::class.companionObject)
|
||||
LOG.info("Companion Object Instance: {}", TestSubject::class.companionObjectInstance)
|
||||
LOG.info("Object Instance: {}", TestObject::class.objectInstance)
|
||||
|
||||
Assert.assertSame(TestObject, TestObject::class.objectInstance)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testNewInstance() {
|
||||
val listClass = ArrayList::class
|
||||
|
||||
val list = listClass.createInstance()
|
||||
Assert.assertTrue(list is ArrayList)
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
fun testMembers() {
|
||||
val bigDecimalClass = BigDecimal::class
|
||||
|
||||
LOG.info("Constructors: {}", bigDecimalClass.constructors)
|
||||
LOG.info("Functions: {}", bigDecimalClass.functions)
|
||||
LOG.info("Properties: {}", bigDecimalClass.memberProperties)
|
||||
LOG.info("Extension Functions: {}", bigDecimalClass.memberExtensionFunctions)
|
||||
}
|
||||
}
|
||||
|
||||
class TestSubject {
|
||||
companion object {
|
||||
val name = "TestSubject"
|
||||
}
|
||||
}
|
||||
|
||||
object TestObject {
|
||||
val answer = 42
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.baeldung.reflection
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.nio.charset.Charset
|
||||
import kotlin.reflect.KMutableProperty
|
||||
import kotlin.reflect.full.starProjectedType
|
||||
|
||||
class KMethodTest {
|
||||
|
||||
@Test
|
||||
fun testCallMethod() {
|
||||
val str = "Hello"
|
||||
val lengthMethod = str::length
|
||||
|
||||
Assert.assertEquals(5, lengthMethod())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testReturnType() {
|
||||
val str = "Hello"
|
||||
val method = str::byteInputStream
|
||||
|
||||
Assert.assertEquals(ByteArrayInputStream::class.starProjectedType, method.returnType)
|
||||
Assert.assertFalse(method.returnType.isMarkedNullable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testParams() {
|
||||
val str = "Hello"
|
||||
val method = str::byteInputStream
|
||||
|
||||
method.isSuspend
|
||||
Assert.assertEquals(1, method.parameters.size)
|
||||
Assert.assertTrue(method.parameters[0].isOptional)
|
||||
Assert.assertFalse(method.parameters[0].isVararg)
|
||||
Assert.assertEquals(Charset::class.starProjectedType, method.parameters[0].type)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMethodDetails() {
|
||||
val codePoints = String::codePoints
|
||||
Assert.assertEquals("codePoints", codePoints.name)
|
||||
Assert.assertFalse(codePoints.isSuspend)
|
||||
Assert.assertFalse(codePoints.isExternal)
|
||||
Assert.assertFalse(codePoints.isInline)
|
||||
Assert.assertFalse(codePoints.isOperator)
|
||||
|
||||
val byteInputStream = String::byteInputStream
|
||||
Assert.assertEquals("byteInputStream", byteInputStream.name)
|
||||
Assert.assertFalse(byteInputStream.isSuspend)
|
||||
Assert.assertFalse(byteInputStream.isExternal)
|
||||
Assert.assertTrue(byteInputStream.isInline)
|
||||
Assert.assertFalse(byteInputStream.isOperator)
|
||||
}
|
||||
|
||||
val readOnlyProperty: Int = 42
|
||||
lateinit var mutableProperty: String
|
||||
|
||||
@Test
|
||||
fun testPropertyDetails() {
|
||||
val roProperty = this::readOnlyProperty
|
||||
Assert.assertEquals("readOnlyProperty", roProperty.name)
|
||||
Assert.assertFalse(roProperty.isLateinit)
|
||||
Assert.assertFalse(roProperty.isConst)
|
||||
Assert.assertFalse(roProperty is KMutableProperty<*>)
|
||||
|
||||
val mProperty = this::mutableProperty
|
||||
Assert.assertEquals("mutableProperty", mProperty.name)
|
||||
Assert.assertTrue(mProperty.isLateinit)
|
||||
Assert.assertFalse(mProperty.isConst)
|
||||
Assert.assertTrue(mProperty is KMutableProperty<*>)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testProperty() {
|
||||
val prop = this::mutableProperty
|
||||
|
||||
Assert.assertEquals(String::class.starProjectedType, prop.getter.returnType)
|
||||
|
||||
prop.set("Hello")
|
||||
Assert.assertEquals("Hello", prop.get())
|
||||
|
||||
prop.setter("World")
|
||||
Assert.assertEquals("World", prop.getter())
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package com.baeldung.regex
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.*
|
||||
|
||||
class RegexTest {
|
||||
|
||||
@Test
|
||||
fun whenRegexIsInstantiated_thenIsEqualToToRegexMethod() {
|
||||
val pattern = """a([bc]+)d?\\"""
|
||||
|
||||
assertEquals(Regex.fromLiteral(pattern).pattern, pattern)
|
||||
assertEquals(pattern, Regex(pattern).pattern)
|
||||
assertEquals(pattern, pattern.toRegex().pattern)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenRegexMatches_thenResultIsTrue() {
|
||||
val regex = """a([bc]+)d?""".toRegex()
|
||||
|
||||
assertTrue(regex.containsMatchIn("xabcdy"))
|
||||
assertTrue(regex.matches("abcd"))
|
||||
assertFalse(regex matches "xabcdy")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenCompletelyMatchingRegex_whenMatchResult_thenDestructuring() {
|
||||
val regex = """a([bc]+)d?""".toRegex()
|
||||
|
||||
assertNull(regex.matchEntire("xabcdy"))
|
||||
|
||||
val matchResult = regex.matchEntire("abbccbbd")
|
||||
|
||||
assertNotNull(matchResult)
|
||||
assertEquals(matchResult!!.value, matchResult.groupValues[0])
|
||||
assertEquals(matchResult.destructured.toList(), matchResult.groupValues.drop(1))
|
||||
assertEquals("bbccbb", matchResult.destructured.component1())
|
||||
assertNull(matchResult.next())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenPartiallyMatchingRegex_whenMatchResult_thenGroups() {
|
||||
val regex = """a([bc]+)d?""".toRegex()
|
||||
var matchResult = regex.find("abcb abbd")
|
||||
|
||||
assertNotNull(matchResult)
|
||||
assertEquals(matchResult!!.value, matchResult.groupValues[0])
|
||||
assertEquals("abcb", matchResult.value)
|
||||
assertEquals(IntRange(0, 3), matchResult.range)
|
||||
assertEquals(listOf("abcb", "bcb"), matchResult.groupValues)
|
||||
assertEquals(matchResult.destructured.toList(), matchResult.groupValues.drop(1))
|
||||
|
||||
matchResult = matchResult.next()
|
||||
|
||||
assertNotNull(matchResult)
|
||||
assertEquals("abbd", matchResult!!.value)
|
||||
assertEquals("bb", matchResult.groupValues[1])
|
||||
|
||||
matchResult = matchResult.next()
|
||||
|
||||
assertNull(matchResult)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenPartiallyMatchingRegex_whenMatchResult_thenDestructuring() {
|
||||
val regex = """([\w\s]+) is (\d+) years old""".toRegex()
|
||||
val matchResult = regex.find("Mickey Mouse is 95 years old")
|
||||
val (name, age) = matchResult!!.destructured
|
||||
|
||||
assertEquals("Mickey Mouse", name)
|
||||
assertEquals("95", age)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenNonMatchingRegex_whenFindCalled_thenNull() {
|
||||
val regex = """a([bc]+)d?""".toRegex()
|
||||
val matchResult = regex.find("foo")
|
||||
|
||||
assertNull(matchResult)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenNonMatchingRegex_whenFindAllCalled_thenEmptySet() {
|
||||
val regex = """a([bc]+)d?""".toRegex()
|
||||
val matchResults = regex.findAll("foo")
|
||||
|
||||
assertNotNull(matchResults)
|
||||
assertTrue(matchResults.none())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReplace_thenReplacement() {
|
||||
val regex = """(red|green|blue)""".toRegex()
|
||||
val beautiful = "Roses are red, Violets are blue"
|
||||
val grim = regex.replace(beautiful, "dark")
|
||||
val shiny = regex.replaceFirst(beautiful, "rainbow")
|
||||
|
||||
assertEquals("Roses are dark, Violets are dark", grim)
|
||||
assertEquals("Roses are rainbow, Violets are blue", shiny)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenComplexReplace_thenReplacement() {
|
||||
val regex = """(red|green|blue)""".toRegex()
|
||||
val beautiful = "Roses are red, Violets are blue"
|
||||
val reallyBeautiful = regex.replace(beautiful) {
|
||||
matchResult -> matchResult.value.toUpperCase() + "!"
|
||||
}
|
||||
|
||||
assertEquals("Roses are RED!, Violets are BLUE!", reallyBeautiful)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenSplit_thenList() {
|
||||
val regex = """\W+""".toRegex()
|
||||
val beautiful = "Roses are red, Violets are blue"
|
||||
|
||||
assertEquals(listOf("Roses", "are", "red", "Violets", "are", "blue"), regex.split(beautiful))
|
||||
assertEquals(listOf("Roses", "are", "red", "Violets are blue"), regex.split(beautiful, 4))
|
||||
assertEquals(regex.toPattern().split(beautiful).asList(), regex.split(beautiful))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
## Core Kotlin Collections
|
||||
|
||||
This module contains articles about core Kotlin collections.
|
||||
|
||||
### Relevant articles:
|
||||
- [Split a List Into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts)
|
||||
- [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list)
|
||||
- [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)
|
||||
- [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection)
|
||||
@@ -0,0 +1,47 @@
|
||||
<?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-collections</artifactId>
|
||||
<name>core-kotlin-collections</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
||||
<artifactId>core-kotlin-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-test</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<kotlin.version>1.3.30</kotlin.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package com.baeldung.collections
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class CollectionsTest {
|
||||
|
||||
@Test
|
||||
fun whenUseDifferentCollections_thenSuccess () {
|
||||
val theList = listOf("one", "two", "three")
|
||||
assertTrue(theList.contains("two"))
|
||||
|
||||
val theMutableList = mutableListOf("one", "two", "three")
|
||||
theMutableList.add("four")
|
||||
assertTrue(theMutableList.contains("four"))
|
||||
|
||||
val theSet = setOf("one", "two", "three")
|
||||
assertTrue(theSet.contains("three"))
|
||||
|
||||
val theMutableSet = mutableSetOf("one", "two", "three")
|
||||
theMutableSet.add("four")
|
||||
assertTrue(theMutableSet.contains("four"))
|
||||
|
||||
val theMap = mapOf(1 to "one", 2 to "two", 3 to "three")
|
||||
assertEquals(theMap[2],"two")
|
||||
|
||||
val theMutableMap = mutableMapOf(1 to "one", 2 to "two", 3 to "three")
|
||||
theMutableMap[4] = "four"
|
||||
assertEquals(theMutableMap[4],"four")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenSliceCollection_thenSuccess () {
|
||||
val theList = listOf("one", "two", "three")
|
||||
val resultList = theList.slice(1..2)
|
||||
|
||||
assertEquals(2, resultList.size)
|
||||
assertTrue(resultList.contains("two"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenJoinTwoCollections_thenSuccess () {
|
||||
val firstList = listOf("one", "two", "three")
|
||||
val secondList = listOf("four", "five", "six")
|
||||
val resultList = firstList + secondList
|
||||
|
||||
assertEquals(6, resultList.size)
|
||||
assertTrue(resultList.contains("two"))
|
||||
assertTrue(resultList.contains("five"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenFilterNullValues_thenSuccess () {
|
||||
val theList = listOf("one", null, "two", null, "three")
|
||||
val resultList = theList.filterNotNull()
|
||||
|
||||
assertEquals(3, resultList.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenFilterNonPositiveValues_thenSuccess () {
|
||||
val theList = listOf(1, 2, -3, -4, 5, -6)
|
||||
val resultList = theList.filter{ it > 0}
|
||||
//val resultList = theList.filter{ x -> x > 0}
|
||||
|
||||
assertEquals(3, resultList.size)
|
||||
assertTrue(resultList.contains(1))
|
||||
assertFalse(resultList.contains(-4))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenDropFirstItems_thenRemoved () {
|
||||
val theList = listOf("one", "two", "three", "four")
|
||||
val resultList = theList.drop(2)
|
||||
|
||||
assertEquals(2, resultList.size)
|
||||
assertFalse(resultList.contains("one"))
|
||||
assertFalse(resultList.contains("two"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenDropFirstItemsBasedOnCondition_thenRemoved () {
|
||||
val theList = listOf("one", "two", "three", "four")
|
||||
val resultList = theList.dropWhile{ it.length < 4 }
|
||||
|
||||
assertEquals(2, resultList.size)
|
||||
assertFalse(resultList.contains("one"))
|
||||
assertFalse(resultList.contains("two"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenExcludeItems_thenRemoved () {
|
||||
val firstList = listOf("one", "two", "three")
|
||||
val secondList = listOf("one", "three")
|
||||
val resultList = firstList - secondList
|
||||
|
||||
assertEquals(1, resultList.size)
|
||||
assertTrue(resultList.contains("two"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenSearchForExistingItem_thenFound () {
|
||||
val theList = listOf("one", "two", "three")
|
||||
|
||||
assertTrue("two" in theList)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGroupItems_thenSuccess () {
|
||||
val theList = listOf(1, 2, 3, 4, 5, 6)
|
||||
val resultMap = theList.groupBy{ it % 3}
|
||||
|
||||
assertEquals(3, resultMap.size)
|
||||
print(resultMap[1])
|
||||
assertTrue(resultMap[1]!!.contains(1))
|
||||
assertTrue(resultMap[2]!!.contains(5))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenApplyFunctionToAllItems_thenSuccess () {
|
||||
val theList = listOf(1, 2, 3, 4, 5, 6)
|
||||
val resultList = theList.map{ it * it }
|
||||
print(resultList)
|
||||
assertEquals(4, resultList[1])
|
||||
assertEquals(9, resultList[2])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenApplyMultiOutputFunctionToAllItems_thenSuccess () {
|
||||
val theList = listOf("John", "Tom")
|
||||
val resultList = theList.flatMap{ it.toLowerCase().toList()}
|
||||
print(resultList)
|
||||
assertEquals(7, resultList.size)
|
||||
assertTrue(resultList.contains('j'))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenApplyFunctionToAllItemsWithStartingValue_thenSuccess () {
|
||||
val theList = listOf(1, 2, 3, 4, 5, 6)
|
||||
val finalResult = theList.fold( 1000, { oldResult, currentItem -> oldResult + (currentItem *currentItem)})
|
||||
print(finalResult)
|
||||
assertEquals(1091, finalResult)
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.filter
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
internal class ChunkedTest {
|
||||
|
||||
@Test
|
||||
fun givenDNAFragmentString_whenChunking_thenProduceListOfChunks() {
|
||||
val dnaFragment = "ATTCGCGGCCGCCAA"
|
||||
|
||||
val fragments = dnaFragment.chunked(3)
|
||||
|
||||
assertIterableEquals(listOf("ATT", "CGC", "GGC", "CGC", "CAA"), fragments)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenDNAString_whenChunkingWithTransformer_thenProduceTransformedList() {
|
||||
val codonTable = mapOf("ATT" to "Isoleucine", "CAA" to "Glutamine", "CGC" to "Arginine", "GGC" to "Glycine")
|
||||
val dnaFragment = "ATTCGCGGCCGCCAA"
|
||||
|
||||
val proteins = dnaFragment.chunked(3) { codon ->
|
||||
codonTable[codon.toString()] ?: error("Unknown codon")
|
||||
}
|
||||
|
||||
assertIterableEquals(listOf("Isoleucine", "Arginine", "Glycine", "Arginine", "Glutamine"), proteins)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenListOfValues_whenChunking_thenProduceListOfArrays() {
|
||||
val whole = listOf(1, 4, 7, 4753, 2, 34, 62, 76, 5868, 0)
|
||||
val chunks = whole.chunked(6)
|
||||
|
||||
val expected = listOf(listOf(1, 4, 7, 4753, 2, 34), listOf(62, 76, 5868, 0))
|
||||
|
||||
assertIterableEquals(expected, chunks)
|
||||
}
|
||||
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.filter
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
internal class DistinctTest {
|
||||
data class SmallClass(val key: String, val num: Int)
|
||||
|
||||
@Test
|
||||
fun whenApplyingDistinct_thenReturnListOfNoDuplicateValues() {
|
||||
val array = arrayOf(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 7, 8, 9)
|
||||
val result = array.distinct()
|
||||
val expected = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
|
||||
|
||||
assertIterableEquals(expected, result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenArrayOfClassObjects_whenApplyingDistinctOnClassProperty_thenReturnListDistinctOnThatValue() {
|
||||
|
||||
val original = arrayOf(
|
||||
SmallClass("key1", 1),
|
||||
SmallClass("key2", 2),
|
||||
SmallClass("key3", 3),
|
||||
SmallClass("key4", 3),
|
||||
SmallClass("er", 9),
|
||||
SmallClass("er", 10),
|
||||
SmallClass("er", 11))
|
||||
|
||||
val actual = original.distinctBy { it.key }
|
||||
|
||||
val expected = listOf(
|
||||
SmallClass("key1", 1),
|
||||
SmallClass("key2", 2),
|
||||
SmallClass("key3", 3),
|
||||
SmallClass("key4", 3),
|
||||
SmallClass("er", 9))
|
||||
|
||||
|
||||
assertIterableEquals(expected, actual)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenArrayOfClassObjects_whenApplyingComplicatedSelector_thenReturnFirstElementToMatchEachSelectorValue() {
|
||||
val array = arrayOf(
|
||||
SmallClass("key1", 1),
|
||||
SmallClass("key2", 2),
|
||||
SmallClass("key3", 3),
|
||||
SmallClass("key4", 3),
|
||||
SmallClass("er", 9),
|
||||
SmallClass("er", 10),
|
||||
SmallClass("er", 11),
|
||||
SmallClass("er", 11),
|
||||
SmallClass("er", 91),
|
||||
SmallClass("blob", 22),
|
||||
SmallClass("dob", 27),
|
||||
SmallClass("high", 201_434_314))
|
||||
|
||||
val actual = array.distinctBy { Math.floor(it.num / 10.0) }
|
||||
|
||||
val expected = listOf(
|
||||
SmallClass("key1", 1),
|
||||
SmallClass("er", 10),
|
||||
SmallClass("er", 91),
|
||||
SmallClass("blob", 22),
|
||||
SmallClass("high", 201_434_314))
|
||||
|
||||
assertIterableEquals(expected, actual)
|
||||
}
|
||||
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.filter
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
internal class DropTest {
|
||||
|
||||
@Test
|
||||
fun whenDroppingFirstTwoItemsOfArray_thenTwoLess() {
|
||||
val array = arrayOf(1, 2, 3, 4)
|
||||
val result = array.drop(2)
|
||||
val expected = listOf(3, 4)
|
||||
|
||||
assertIterableEquals(expected, result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenDroppingMoreItemsOfArray_thenEmptyList() {
|
||||
val array = arrayOf(1, 2, 3, 4)
|
||||
val result = array.drop(5)
|
||||
val expected = listOf<Int>()
|
||||
|
||||
assertIterableEquals(expected, result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenArray_whenDroppingLastElement_thenReturnListWithoutLastElement() {
|
||||
val array = arrayOf("1", "2", "3", "4")
|
||||
val result = array.dropLast(1)
|
||||
val expected = listOf("1", "2", "3")
|
||||
|
||||
assertIterableEquals(expected, result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenArrayOfFloats_whenDroppingLastUntilPredicateIsFalse_thenReturnSubsetListOfFloats() {
|
||||
val array = arrayOf(1f, 1f, 1f, 1f, 1f, 2f, 1f, 1f, 1f)
|
||||
val result = array.dropLastWhile { it == 1f }
|
||||
val expected = listOf(1f, 1f, 1f, 1f, 1f, 2f)
|
||||
|
||||
assertIterableEquals(expected, result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenList_whenDroppingMoreThanAvailable_thenThrowException() {
|
||||
val list = listOf('a', 'e', 'i', 'o', 'u')
|
||||
val result = list.drop(6)
|
||||
val expected: List<String> = listOf()
|
||||
|
||||
assertIterableEquals(expected, result)
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.filter
|
||||
|
||||
import org.apache.commons.math3.primes.Primes
|
||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
internal class FilterTest {
|
||||
|
||||
@Test
|
||||
fun givenAscendingValueMap_whenFilteringOnValue_ThenReturnSubsetOfMap() {
|
||||
val originalMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
|
||||
val filteredMap = originalMap.filter { it.value < 2 }
|
||||
val expectedMap = mapOf("key1" to 1)
|
||||
|
||||
assertTrue { expectedMap == filteredMap }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenSeveralCollections_whenFilteringToAccumulativeList_thenListContainsAllContents() {
|
||||
val array1 = arrayOf(90, 92, 93, 94, 92, 95, 93)
|
||||
val array2 = sequenceOf(51, 31, 83, 674_506_111, 256_203_161, 15_485_863)
|
||||
val list1 = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
|
||||
val primes = mutableListOf<Int>()
|
||||
|
||||
val expected = listOf(2, 3, 5, 7, 31, 83, 15_485_863, 256_203_161, 674_506_111)
|
||||
|
||||
val primeCheck = { num: Int -> Primes.isPrime(num) }
|
||||
|
||||
array1.filterTo(primes, primeCheck)
|
||||
list1.filterTo(primes, primeCheck)
|
||||
array2.filterTo(primes, primeCheck)
|
||||
|
||||
primes.sort()
|
||||
|
||||
assertIterableEquals(expected, primes)
|
||||
}
|
||||
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.filter
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
||||
import org.junit.jupiter.api.Assertions.assertThrows
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
internal class SliceTest {
|
||||
|
||||
@Test
|
||||
fun whenSlicingAnArrayWithDotRange_ThenListEqualsTheSlice() {
|
||||
val original = arrayOf(1, 2, 3, 2, 1)
|
||||
val actual = original.slice(1..3)
|
||||
val expected = listOf(2, 3, 2)
|
||||
|
||||
assertIterableEquals(expected, actual)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenSlicingAnArrayWithDownToRange_thenListMadeUpOfReverseSlice() {
|
||||
val original = arrayOf(1, 2, 3, 2, 1)
|
||||
val actual = original.slice(3 downTo 0)
|
||||
val expected = listOf(2, 3, 2, 1)
|
||||
|
||||
assertIterableEquals(expected, actual)
|
||||
}
|
||||
|
||||
// From the 1.3 version of Kotlin APIs, slice doesn't return array of nulls but throw IndexOutOfBoundsException
|
||||
// @Test
|
||||
// fun whenSlicingBeyondTheRangeOfTheArray_thenContainManyNulls() {
|
||||
// val original = arrayOf(12, 3, 34, 4)
|
||||
// val actual = original.slice(3..8)
|
||||
// val expected = listOf(4, null, null, null, null, null)
|
||||
//
|
||||
// assertIterableEquals(expected, actual)
|
||||
// }
|
||||
|
||||
@Test
|
||||
fun whenSlicingBeyondRangeOfArrayWithStep_thenOutOfBoundsException() {
|
||||
assertThrows(ArrayIndexOutOfBoundsException::class.java) {
|
||||
val original = arrayOf(12, 3, 34, 4)
|
||||
original.slice(3..8 step 2)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.filter
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertIterableEquals
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
internal class TakeTest {
|
||||
|
||||
@Test
|
||||
fun `given array of alternating types, when predicating on 'is String', then produce list of array up until predicate is false`() {
|
||||
val originalArray = arrayOf("val1", 2, "val3", 4, "val5", 6)
|
||||
val actualList = originalArray.takeWhile { it is String }
|
||||
val expectedList = listOf("val1")
|
||||
|
||||
assertIterableEquals(expectedList, actualList)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `given array of alternating types, when taking 4 items, then produce list of first 4 items`() {
|
||||
val originalArray = arrayOf("val1", 2, "val3", 4, "val5", 6)
|
||||
val actualList = originalArray.take(4)
|
||||
val expectedList = listOf("val1", 2, "val3", 4)
|
||||
|
||||
println(originalArray.drop(4))
|
||||
println(actualList)
|
||||
|
||||
assertIterableEquals(expectedList, actualList)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `when taking more items than available, then return all elements`() {
|
||||
val originalArray = arrayOf(1, 2)
|
||||
val actual = originalArray.take(10)
|
||||
val expected = listOf(1, 2)
|
||||
|
||||
assertIterableEquals(expected, actual)
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.findelement
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class FindAnElementInAListUnitTest {
|
||||
|
||||
var batmans: List<String> = listOf("Christian Bale", "Michael Keaton", "Ben Affleck", "George Clooney")
|
||||
|
||||
@Test
|
||||
fun whenFindASpecificItem_thenItemIsReturned() {
|
||||
//Returns the first element matching the given predicate, or null if no such element was found.
|
||||
val theFirstBatman = batmans.find { actor -> "Michael Keaton".equals(actor) }
|
||||
assertEquals(theFirstBatman, "Michael Keaton")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenFilterWithPredicate_thenMatchingItemsAreReturned() {
|
||||
//Returns a list containing only elements matching the given predicate.
|
||||
val theCoolestBatmans = batmans.filter { actor -> actor.contains("a") }
|
||||
assertTrue(theCoolestBatmans.contains("Christian Bale") && theCoolestBatmans.contains("Michael Keaton"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenFilterNotWithPredicate_thenMatchingItemsAreReturned() {
|
||||
//Returns a list containing only elements not matching the given predicate.
|
||||
val theMehBatmans = batmans.filterNot { actor -> actor.contains("a") }
|
||||
assertFalse(theMehBatmans.contains("Christian Bale") && theMehBatmans.contains("Michael Keaton"))
|
||||
assertTrue(theMehBatmans.contains("Ben Affleck") && theMehBatmans.contains("George Clooney"))
|
||||
}
|
||||
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.listtomap
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class ListToMapTest {
|
||||
|
||||
val user1 = User("John", 18, listOf("Hiking, Swimming"))
|
||||
val user2 = User("Sara", 25, listOf("Chess, Board Games"))
|
||||
val user3 = User("Dave", 34, listOf("Games, Racing sports"))
|
||||
val user4 = User("John", 30, listOf("Reading, Poker"))
|
||||
|
||||
@Test
|
||||
fun givenList_whenConvertToMap_thenResult() {
|
||||
val myList = listOf(user1, user2, user3)
|
||||
val myMap = myList.map { it.name to it.age }.toMap()
|
||||
|
||||
assertTrue(myMap.get("John") == 18)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenList_whenAssociatedBy_thenResult() {
|
||||
val myList = listOf(user1, user2, user3)
|
||||
val myMap = myList.associateBy({ it.name }, { it.hobbies })
|
||||
|
||||
assertTrue(myMap.get("John")!!.contains("Hiking, Swimming"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenStringList_whenConvertToMap_thenResult() {
|
||||
val myList = listOf("a", "b", "c")
|
||||
val myMap = myList.map { it to it }.toMap()
|
||||
|
||||
assertTrue(myMap.get("a") == "a")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenStringList_whenAssociate_thenResult() {
|
||||
val myList = listOf("a", "b", "c", "c", "b")
|
||||
val myMap = myList.associate{ it to it }
|
||||
|
||||
assertTrue(myMap.get("a") == "a")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenStringList_whenAssociateTo_thenResult() {
|
||||
val myList = listOf("a", "b", "c", "c", "b")
|
||||
val myMap = mutableMapOf<String, String>()
|
||||
|
||||
myList.associateTo(myMap) {it to it}
|
||||
|
||||
assertTrue(myMap.get("a") == "a")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenStringList_whenAssociateByTo_thenResult() {
|
||||
val myList = listOf(user1, user2, user3, user4)
|
||||
val myMap = mutableMapOf<String, Int>()
|
||||
|
||||
myList.associateByTo(myMap, {it.name}, {it.age})
|
||||
|
||||
assertTrue(myMap.get("Dave") == 34)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenStringList_whenAssociateByToUser_thenResult() {
|
||||
val myList = listOf(user1, user2, user3, user4)
|
||||
val myMap = mutableMapOf<String, User>()
|
||||
|
||||
myList.associateByTo(myMap) {it.name}
|
||||
|
||||
assertTrue(myMap.get("Dave")!!.age == 34)
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.listtomap
|
||||
|
||||
data class User(val name: String, val age: Int, val hobbies: List<String>)
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.baeldung.splitlist
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class SplitListIntoPartsTest {
|
||||
private val evenList = listOf(0, "a", 1, "b", 2, "c");
|
||||
|
||||
private val unevenList = listOf(0, "a", 1, "b", 2, "c", 3);
|
||||
|
||||
private fun verifyList(resultList: List<List<Any>>) {
|
||||
assertEquals("[[0, a], [1, b], [2, c]]", resultList.toString())
|
||||
}
|
||||
|
||||
private fun verifyPartialList(resultList: List<List<Any>>) {
|
||||
assertEquals("[[0, a], [1, b], [2, c], [3]]", resultList.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenChunked_thenListIsSplit() {
|
||||
val resultList = evenList.chunked(2)
|
||||
verifyList(resultList)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenUnevenChunked_thenListIsSplit() {
|
||||
val resultList = unevenList.chunked(2)
|
||||
verifyPartialList(resultList)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenWindowed_thenListIsSplit() {
|
||||
val resultList = evenList.windowed(2, 2)
|
||||
verifyList(resultList)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenUnevenPartialWindowed_thenListIsSplit() {
|
||||
val resultList = unevenList.windowed(2, 2, partialWindows = true)
|
||||
verifyPartialList(resultList)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenUnevenWindowed_thenListIsSplit() {
|
||||
val resultList = unevenList.windowed(2, 2, partialWindows = false)
|
||||
verifyList(resultList)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGroupByWithAscendingNumbers_thenListIsSplit() {
|
||||
val numberList = listOf(1, 2, 3, 4, 5, 6);
|
||||
val resultList = numberList.groupBy { (it + 1) / 2 }
|
||||
assertEquals("[[1, 2], [3, 4], [5, 6]]", resultList.values.toString())
|
||||
assertEquals("[1, 2, 3]", resultList.keys.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGroupByWithAscendingNumbersUneven_thenListIsSplit() {
|
||||
val numberList = listOf(1, 2, 3, 4, 5, 6, 7);
|
||||
val resultList = numberList.groupBy { (it + 1) / 2 }.values
|
||||
assertEquals("[[1, 2], [3, 4], [5, 6], [7]]", resultList.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGroupByWithRandomNumbers_thenListIsSplitInWrongWay() {
|
||||
val numberList = listOf(1, 3, 8, 20, 23, 30);
|
||||
val resultList = numberList.groupBy { (it + 1) / 2 }
|
||||
assertEquals("[[1], [3], [8], [20], [23], [30]]", resultList.values.toString())
|
||||
assertEquals("[1, 2, 4, 10, 12, 15]", resultList.keys.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenWithIndexGroupBy_thenListIsSplit() {
|
||||
val resultList = evenList.withIndex()
|
||||
.groupBy { it.index / 2 }
|
||||
.map { it.value.map { it.value } }
|
||||
verifyList(resultList)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenWithIndexGroupByUneven_thenListIsSplit() {
|
||||
val resultList = unevenList.withIndex()
|
||||
.groupBy { it.index / 2 }
|
||||
.map { it.value.map { it.value } }
|
||||
verifyPartialList(resultList)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenFoldIndexed_thenListIsSplit() {
|
||||
val resultList = evenList.foldIndexed(ArrayList<ArrayList<Any>>(evenList.size / 2)) { index, acc, item ->
|
||||
if (index % 2 == 0) {
|
||||
acc.add(ArrayList(2))
|
||||
}
|
||||
acc.last().add(item)
|
||||
acc
|
||||
}
|
||||
verifyList(resultList)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
## Core Kotlin Concurrency
|
||||
|
||||
This module contains articles about concurrency in Kotlin.
|
||||
|
||||
### Relevant articles:
|
||||
- [Threads vs Coroutines in Kotlin](https://www.baeldung.com/kotlin-threads-coroutines)
|
||||
- [Introduction to Kotlin Coroutines](https://www.baeldung.com/kotlin-coroutines)
|
||||
@@ -0,0 +1,41 @@
|
||||
<?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-concurrency</artifactId>
|
||||
<name>core-kotlin-concurrency</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
||||
<artifactId>core-kotlin-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-test</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<kotlin.version>1.3.30</kotlin.version>
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.threadsvscoroutines
|
||||
|
||||
class SimpleRunnable: Runnable {
|
||||
|
||||
override fun run() {
|
||||
println("${Thread.currentThread()} has run.")
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.threadsvscoroutines
|
||||
|
||||
class SimpleThread: Thread() {
|
||||
|
||||
override fun run() {
|
||||
println("${Thread.currentThread()} has run.")
|
||||
}
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
package com.baeldung.coroutines
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import kotlin.system.measureTimeMillis
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
|
||||
class CoroutinesTest {
|
||||
|
||||
@Test
|
||||
fun givenBuildSequence_whenTakeNElements_thenShouldReturnItInALazyWay() {
|
||||
//given
|
||||
val fibonacciSeq = sequence {
|
||||
var a = 0
|
||||
var b = 1
|
||||
|
||||
yield(1)
|
||||
|
||||
while (true) {
|
||||
yield(a + b)
|
||||
|
||||
val tmp = a + b
|
||||
a = b
|
||||
b = tmp
|
||||
}
|
||||
}
|
||||
|
||||
//when
|
||||
val res = fibonacciSeq.take(5).toList()
|
||||
|
||||
//then
|
||||
assertEquals(res, listOf(1, 1, 2, 3, 5))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenLazySeq_whenTakeNElements_thenShouldReturnAllElements() {
|
||||
//given
|
||||
val lazySeq = sequence {
|
||||
print("START ")
|
||||
for (i in 1..5) {
|
||||
yield(i)
|
||||
print("STEP ")
|
||||
}
|
||||
print("END")
|
||||
}
|
||||
//when
|
||||
val res = lazySeq.take(10).toList()
|
||||
|
||||
//then
|
||||
assertEquals(res, listOf(1, 2, 3, 4, 5))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenAsyncCoroutine_whenStartIt_thenShouldExecuteItInTheAsyncWay() {
|
||||
//given
|
||||
val res = mutableListOf<String>()
|
||||
|
||||
//when
|
||||
runBlocking {
|
||||
val promise = launch(Dispatchers.Default) { expensiveComputation(res) }
|
||||
res.add("Hello,")
|
||||
promise.join()
|
||||
}
|
||||
|
||||
//then
|
||||
assertEquals(res, listOf("Hello,", "word!"))
|
||||
}
|
||||
|
||||
|
||||
suspend fun expensiveComputation(res: MutableList<String>) {
|
||||
delay(1000L)
|
||||
res.add("word!")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenHugeAmountOfCoroutines_whenStartIt_thenShouldExecuteItWithoutOutOfMemory() {
|
||||
runBlocking<Unit> {
|
||||
//given
|
||||
val counter = AtomicInteger(0)
|
||||
val numberOfCoroutines = 100_000
|
||||
|
||||
//when
|
||||
val jobs = List(numberOfCoroutines) {
|
||||
launch(Dispatchers.Default) {
|
||||
delay(1L)
|
||||
counter.incrementAndGet()
|
||||
}
|
||||
}
|
||||
jobs.forEach { it.join() }
|
||||
|
||||
//then
|
||||
assertEquals(counter.get(), numberOfCoroutines)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenCancellableJob_whenRequestForCancel_thenShouldQuit() {
|
||||
runBlocking<Unit> {
|
||||
//given
|
||||
val job = launch(Dispatchers.Default) {
|
||||
while (isActive) {
|
||||
//println("is working")
|
||||
}
|
||||
}
|
||||
|
||||
delay(1300L)
|
||||
|
||||
//when
|
||||
job.cancel()
|
||||
|
||||
//then cancel successfully
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = CancellationException::class)
|
||||
fun givenAsyncAction_whenDeclareTimeout_thenShouldFinishWhenTimedOut() {
|
||||
runBlocking<Unit> {
|
||||
withTimeout(1300L) {
|
||||
repeat(1000) { i ->
|
||||
println("Some expensive computation $i ...")
|
||||
delay(500L)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenHaveTwoExpensiveAction_whenExecuteThemAsync_thenTheyShouldRunConcurrently() {
|
||||
runBlocking<Unit> {
|
||||
val delay = 1000L
|
||||
val time = measureTimeMillis {
|
||||
//given
|
||||
val one = async(Dispatchers.Default) { someExpensiveComputation(delay) }
|
||||
val two = async(Dispatchers.Default) { someExpensiveComputation(delay) }
|
||||
|
||||
//when
|
||||
runBlocking {
|
||||
one.await()
|
||||
two.await()
|
||||
}
|
||||
}
|
||||
|
||||
//then
|
||||
assertTrue(time < delay * 2)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenTwoExpensiveAction_whenExecuteThemLazy_thenTheyShouldNotConcurrently() {
|
||||
runBlocking<Unit> {
|
||||
val delay = 1000L
|
||||
val time = measureTimeMillis {
|
||||
//given
|
||||
val one = async(Dispatchers.Default, CoroutineStart.LAZY) { someExpensiveComputation(delay) }
|
||||
val two = async(Dispatchers.Default, CoroutineStart.LAZY) { someExpensiveComputation(delay) }
|
||||
|
||||
//when
|
||||
runBlocking {
|
||||
one.await()
|
||||
two.await()
|
||||
}
|
||||
}
|
||||
|
||||
//then
|
||||
assertTrue(time > delay * 2)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun someExpensiveComputation(delayInMilliseconds: Long) {
|
||||
delay(delayInMilliseconds)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.threadsvscoroutines
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class CoroutineUnitTest {
|
||||
|
||||
@Test
|
||||
fun whenCreateCoroutineWithLaunchWithoutContext_thenRun() = runBlocking {
|
||||
|
||||
val job = launch {
|
||||
println("${Thread.currentThread()} has run.")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenCreateCoroutineWithLaunchWithDefaultContext_thenRun() = runBlocking {
|
||||
|
||||
val job = launch(Dispatchers.Default) {
|
||||
println("${Thread.currentThread()} has run.")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenCreateCoroutineWithLaunchWithUnconfinedContext_thenRun() = runBlocking {
|
||||
|
||||
val job = launch(Dispatchers.Unconfined) {
|
||||
println("${Thread.currentThread()} has run.")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenCreateCoroutineWithLaunchWithDedicatedThread_thenRun() = runBlocking {
|
||||
|
||||
val job = launch(newSingleThreadContext("dedicatedThread")) {
|
||||
println("${Thread.currentThread()} has run.")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenCreateAsyncCoroutine_thenRun() = runBlocking {
|
||||
|
||||
val deferred = async(Dispatchers.IO) {
|
||||
return@async "${Thread.currentThread()} has run."
|
||||
}
|
||||
|
||||
val result = deferred.await()
|
||||
println(result)
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.threadsvscoroutines
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
class ThreadUnitTest {
|
||||
|
||||
@Test
|
||||
fun whenCreateThread_thenRun() {
|
||||
|
||||
val thread = SimpleThread()
|
||||
thread.start()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenCreateThreadWithRunnable_thenRun() {
|
||||
|
||||
val threadWithRunnable = Thread(SimpleRunnable())
|
||||
threadWithRunnable.start()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenCreateThreadWithSAMConversions_thenRun() {
|
||||
|
||||
val thread = Thread {
|
||||
println("${Thread.currentThread()} has run.")
|
||||
}
|
||||
thread.start()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenCreateThreadWithMethodExtension_thenRun() {
|
||||
|
||||
thread(start = true) {
|
||||
println("${Thread.currentThread()} has run.")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,10 @@
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>core-kotlin-advanced</module>
|
||||
<module>core-kotlin-annotations</module>
|
||||
<module>core-kotlin-collections</module>
|
||||
<module>core-kotlin-concurrency</module>
|
||||
<module>core-kotlin-io</module>
|
||||
<module>core-kotlin-lang</module>
|
||||
<module>core-kotlin-lang-2</module>
|
||||
|
||||
Reference in New Issue
Block a user