[BAEL-19882] - Move articles out of core-kotlin part1

This commit is contained in:
catalin-burcea
2019-12-10 14:57:11 +02:00
parent 3517462948
commit a141ac01fd
42 changed files with 210 additions and 124 deletions

View File

@@ -0,0 +1,8 @@
## 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)

View File

@@ -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-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>

View File

@@ -0,0 +1,7 @@
package com.baeldung.annotations
@Target(AnnotationTarget.FIELD)
annotation class Positive
@Target(AnnotationTarget.FIELD)
annotation class AllowedNames(val names: Array<String>)

View File

@@ -0,0 +1,3 @@
package com.baeldung.annotations
class Item(@Positive val amount: Float, @AllowedNames(["Alice", "Bob"]) val name: String)

View File

@@ -0,0 +1,7 @@
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)}")
}

View File

@@ -0,0 +1,38 @@
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
}
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.jvmannotations
import java.util.*
interface Document {
@JvmDefault
fun getTypeDefault() = "document"
fun getType() = "document"
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.jvmannotations;
public class HtmlDocument implements Document {
@Override
public String getType() {
return "HTML";
}
}

View File

@@ -0,0 +1,66 @@
@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>) {
}
}

View File

@@ -0,0 +1,6 @@
@file:JvmMultifileClass
@file:JvmName("MessageHelper") //applies to all top level functions / variables / constants
package com.baeldung.jvmannotations
fun convert(message: Message) {
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.jvmannotations
import java.util.*
class TextDocument : Document {
override fun getType() = "text"
fun transformList(list : List<Number>) : List<Number> {
return list.filter { n -> n.toInt() > 1 }
}
fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> {
return list.filter { n -> n.toInt() > 1 }
}
var list : List<@JvmWildcard Any> = ArrayList()
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.jvmannotations
import java.util.*
class XmlDocument(d : Document) : Document by d

View File

@@ -0,0 +1,12 @@
package com.baeldung.jvmfield
class JvmSample(text:String) {
@JvmField
val sampleText:String = text
}
class CompanionSample {
companion object {
@JvmField val MAX_LIMIT = 20
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.annotations
import org.junit.Test
import kotlin.test.assertTrue
import kotlin.test.assertFalse
class ValidationTest {
@Test
fun whenAmountIsOneAndNameIsAlice_thenTrue() {
assertTrue(Validator().isValid(Item(1f, "Alice")))
}
@Test
fun whenAmountIsOneAndNameIsBob_thenTrue() {
assertTrue(Validator().isValid(Item(1f, "Bob")))
}
@Test
fun whenAmountIsMinusOneAndNameIsAlice_thenFalse() {
assertFalse(Validator().isValid(Item(-1f, "Alice")))
}
@Test
fun whenAmountIsMinusOneAndNameIsBob_thenFalse() {
assertFalse(Validator().isValid(Item(-1f, "Bob")))
}
@Test
fun whenAmountIsOneAndNameIsTom_thenFalse() {
assertFalse(Validator().isValid(Item(1f, "Tom")))
}
@Test
fun whenAmountIsMinusOneAndNameIsTom_thenFalse() {
assertFalse(Validator().isValid(Item(-1f, "Tom")))
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.range
import org.junit.Test
import kotlin.test.assertEquals
import com.baeldung.jvmannotations.*;
class DocumentTest {
@Test
fun testDefaultMethod() {
val myDocument = TextDocument()
val myTextDocument = XmlDocument(myDocument)
assertEquals("text", myDocument.getType())
assertEquals("text", myTextDocument.getType())
assertEquals("document", myTextDocument.getTypeDefault())
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.jvmfield
import org.junit.Before
import org.junit.Test
import kotlin.test.assertTrue
class JvmSampleTest {
var sample = ""
@Before
fun setUp() {
sample = JvmSample("Hello!").sampleText
}
@Test
fun givenField_whenCheckValue_thenMatchesValue() {
assertTrue(sample == "Hello!")
}
@Test
fun givenStaticVariable_whenCheckValue_thenMatchesValue() {
// Sample when is treated as a static variable
assertTrue(CompanionSample.MAX_LIMIT == 20)
}
}