Merge pull request #10273 from eugenp/JAVA-1580
remove kotlin code from repo
This commit is contained in:
@@ -1,11 +0,0 @@
|
||||
## 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)
|
||||
@@ -1,41 +0,0 @@
|
||||
<?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
@@ -1,23 +0,0 @@
|
||||
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
@@ -1,43 +0,0 @@
|
||||
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
@@ -1,10 +0,0 @@
|
||||
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
@@ -1,22 +0,0 @@
|
||||
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
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.datamapping
|
||||
|
||||
data class UserView(
|
||||
val name: String,
|
||||
val address: String,
|
||||
val telephone: String,
|
||||
val age: Int
|
||||
)
|
||||
@@ -1,114 +0,0 @@
|
||||
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
@@ -1,30 +0,0 @@
|
||||
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
@@ -1,30 +0,0 @@
|
||||
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
@@ -1,17 +0,0 @@
|
||||
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
@@ -1,47 +0,0 @@
|
||||
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
@@ -1,44 +0,0 @@
|
||||
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")
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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
@@ -1,43 +0,0 @@
|
||||
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
@@ -1,73 +0,0 @@
|
||||
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
@@ -1,32 +0,0 @@
|
||||
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
@@ -1,69 +0,0 @@
|
||||
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
@@ -1,88 +0,0 @@
|
||||
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
@@ -1,123 +0,0 @@
|
||||
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))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
## Core Kotlin Annotations
|
||||
|
||||
This module contains articles about core Kotlin annotations.
|
||||
|
||||
### Relevant articles:
|
||||
- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations)
|
||||
- [Guide to Kotlin @JvmField](https://www.baeldung.com/kotlin-jvm-field-annotation)
|
||||
- [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations)
|
||||
@@ -1,41 +0,0 @@
|
||||
<?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-annotations</artifactId>
|
||||
<name>core-kotlin-annotations</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>
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.annotations
|
||||
|
||||
@Target(AnnotationTarget.FIELD)
|
||||
annotation class Positive
|
||||
|
||||
@Target(AnnotationTarget.FIELD)
|
||||
annotation class AllowedNames(val names: Array<String>)
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
package com.baeldung.annotations
|
||||
|
||||
class Item(@Positive val amount: Float, @AllowedNames(["Alice", "Bob"]) val name: String)
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.annotations
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val item = Item(amount = 1.0f, name = "Bob")
|
||||
val validator = Validator()
|
||||
println("Is instance valid? ${validator.isValid(item)}")
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package com.baeldung.annotations
|
||||
|
||||
/**
|
||||
* Naive annotation-based validator.
|
||||
* @author A.Shcherbakov
|
||||
*/
|
||||
class Validator() {
|
||||
|
||||
/**
|
||||
* Return true if every item's property annotated with @Positive is positive and if
|
||||
* every item's property annotated with @AllowedNames has a value specified in that annotation.
|
||||
*/
|
||||
fun isValid(item: Item): Boolean {
|
||||
val fields = item::class.java.declaredFields
|
||||
for (field in fields) {
|
||||
field.isAccessible = true
|
||||
for (annotation in field.annotations) {
|
||||
val value = field.get(item)
|
||||
if (field.isAnnotationPresent(Positive::class.java)) {
|
||||
val amount = value as Float
|
||||
if (amount < 0) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if (field.isAnnotationPresent(AllowedNames::class.java)) {
|
||||
val allowedNames = field.getAnnotation(AllowedNames::class.java)?.names
|
||||
val name = value as String
|
||||
allowedNames?.let {
|
||||
if (!it.contains(name)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.jvmannotations
|
||||
|
||||
import java.util.*
|
||||
|
||||
interface Document {
|
||||
|
||||
@JvmDefault
|
||||
fun getTypeDefault() = "document"
|
||||
|
||||
fun getType() = "document"
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.jvmannotations;
|
||||
|
||||
public class HtmlDocument implements Document {
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return "HTML";
|
||||
}
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
@file:JvmName("MessageHelper")
|
||||
@file:JvmMultifileClass //used
|
||||
package com.baeldung.jvmannotations
|
||||
|
||||
import java.util.*
|
||||
|
||||
@JvmName("getMyUsername")
|
||||
fun getMyName() : String {
|
||||
return "myUserId"
|
||||
}
|
||||
|
||||
object MessageBroker {
|
||||
@JvmStatic
|
||||
var totalMessagesSent = 0
|
||||
|
||||
const val maxMessageLength = 0
|
||||
|
||||
@JvmStatic
|
||||
fun clearAllMessages() {
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
@JvmOverloads
|
||||
@Throws(Exception::class)
|
||||
fun findMessages(sender : String, type : String = "text", maxResults : Int = 10) : List<Message> {
|
||||
if(sender.isEmpty()) {
|
||||
throw Exception()
|
||||
}
|
||||
return ArrayList()
|
||||
}
|
||||
}
|
||||
|
||||
class Message {
|
||||
|
||||
// this would cause a compilation error since sender is immutable
|
||||
// @set:JvmName("setSender")
|
||||
val sender = "myself"
|
||||
|
||||
// this works as name is overridden
|
||||
@JvmName("getSenderName")
|
||||
fun getSender() : String = "from:$sender"
|
||||
|
||||
@get:JvmName("getReceiverName")
|
||||
@set:JvmName("setReceiverName")
|
||||
var receiver : String = ""
|
||||
|
||||
@get:JvmName("getContent")
|
||||
@set:JvmName("setContent")
|
||||
var text = ""
|
||||
|
||||
// generates a warning
|
||||
@get:JvmName("getId")
|
||||
private val id = 0
|
||||
|
||||
@get:JvmName("hasAttachment")
|
||||
var hasAttachment = true
|
||||
|
||||
var isEncrypted = true
|
||||
|
||||
fun setReceivers(receiverNames : List<String>) {
|
||||
}
|
||||
|
||||
@JvmName("setReceiverIds")
|
||||
fun setReceivers(receiverNames : List<Int>) {
|
||||
}
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
@file:JvmMultifileClass
|
||||
@file:JvmName("MessageHelper") //applies to all top level functions / variables / constants
|
||||
package com.baeldung.jvmannotations
|
||||
|
||||
fun convert(message: Message) {
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user