This commit is contained in:
17
core-kotlin-modules/core-kotlin-lang-oop/README.md
Normal file
17
core-kotlin-modules/core-kotlin-lang-oop/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
## Core Kotlin Lang OOP
|
||||
|
||||
This module contains articles about core Kotlin language OOP.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Data Classes in Kotlin](https://www.baeldung.com/kotlin-data-classes)
|
||||
- [Sealed Classes in Kotlin](https://www.baeldung.com/kotlin-sealed-classes)
|
||||
- [Extension Methods in Kotlin](https://www.baeldung.com/kotlin-extension-methods)
|
||||
- [Objects in Kotlin](https://www.baeldung.com/kotlin-objects)
|
||||
- [Working with Enums in Kotlin](https://www.baeldung.com/kotlin-enum)
|
||||
- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors)
|
||||
- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes)
|
||||
- [Guide to Kotlin Interfaces](https://www.baeldung.com/kotlin-interfaces)
|
||||
- [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes)
|
||||
- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods)
|
||||
- More articles: [[next -->]](/core-kotlin-lang-oop-2)
|
||||
25
core-kotlin-modules/core-kotlin-lang-oop/pom.xml
Normal file
25
core-kotlin-modules/core-kotlin-lang-oop/pom.xml
Normal file
@@ -0,0 +1,25 @@
|
||||
<?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-lang-oop</artifactId>
|
||||
<name>core-kotlin-lang-oop</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.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.constructor
|
||||
|
||||
class Car {
|
||||
val id: String
|
||||
val type: String
|
||||
|
||||
constructor(id: String, type: String) {
|
||||
this.id = id
|
||||
this.type = type
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val car = Car("1", "sport")
|
||||
val s= Car("2", "suv")
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.constructor
|
||||
|
||||
class Employee(name: String, val salary: Int): Person(name)
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.constructor;
|
||||
|
||||
class PersonJava {
|
||||
final String name;
|
||||
final String surname;
|
||||
final Integer age;
|
||||
|
||||
public PersonJava(String name, String surname) {
|
||||
this.name = name;
|
||||
this.surname = surname;
|
||||
this.age = null;
|
||||
}
|
||||
|
||||
public PersonJava(String name, String surname, Integer age) {
|
||||
this.name = name;
|
||||
this.surname = surname;
|
||||
this.age = age;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.baeldung.dataclass;
|
||||
|
||||
public class Movie {
|
||||
|
||||
private String name;
|
||||
private String studio;
|
||||
private float rating;
|
||||
|
||||
public Movie(String name, String studio, float rating) {
|
||||
this.name = name;
|
||||
this.studio = studio;
|
||||
this.rating = rating;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getStudio() {
|
||||
return studio;
|
||||
}
|
||||
|
||||
public void setStudio(String studio) {
|
||||
this.studio = studio;
|
||||
}
|
||||
|
||||
public float getRating() {
|
||||
return rating;
|
||||
}
|
||||
|
||||
public void setRating(float rating) {
|
||||
this.rating = rating;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
result = prime * result + Float.floatToIntBits(rating);
|
||||
result = prime * result + ((studio == null) ? 0 : studio.hashCode());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
|
||||
if (obj == null)
|
||||
return false;
|
||||
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
|
||||
Movie other = (Movie) obj;
|
||||
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
|
||||
if (Float.floatToIntBits(rating) != Float.floatToIntBits(other.rating))
|
||||
return false;
|
||||
|
||||
if (studio == null) {
|
||||
if (other.studio != null)
|
||||
return false;
|
||||
|
||||
} else if (!studio.equals(other.studio))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Movie [name=" + name + ", studio=" + studio + ", rating=" + rating + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.constructor
|
||||
|
||||
open class Person(
|
||||
val name: String,
|
||||
val age: Int? = null
|
||||
) {
|
||||
val upperCaseName: String = name.toUpperCase()
|
||||
|
||||
init {
|
||||
println("Hello, I'm $name")
|
||||
|
||||
if (age != null && age < 0) {
|
||||
throw IllegalArgumentException("Age cannot be less than zero!")
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
println("upperCaseName is $upperCaseName")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val person = Person("John")
|
||||
val personWithAge = Person("John", 22)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.dataclass
|
||||
|
||||
data class Movie(val name: String, val studio: String, var rating: Float)
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.dataclass
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
val movie = Movie("Whiplash", "Sony Pictures", 8.5F)
|
||||
|
||||
println(movie.name) //Whiplash
|
||||
println(movie.studio) //Sony Pictures
|
||||
println(movie.rating) //8.5
|
||||
|
||||
movie.rating = 9F
|
||||
|
||||
println(movie.toString()) //Movie(name=Whiplash, studio=Sony Pictures, rating=9.0)
|
||||
|
||||
val betterRating = movie.copy(rating = 9.5F)
|
||||
println(betterRating.toString()) //Movie(name=Whiplash, studio=Sony Pictures, rating=9.5)
|
||||
|
||||
movie.component1() //name
|
||||
movie.component2() //studio
|
||||
movie.component3() //rating
|
||||
|
||||
val(name, studio, rating) = movie
|
||||
|
||||
fun getMovieInfo() = movie
|
||||
val(namef, studiof, ratingf) = getMovieInfo()
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.enums
|
||||
|
||||
enum class CardType(val color: String) : ICardLimit {
|
||||
SILVER("gray") {
|
||||
override fun getCreditLimit() = 100000
|
||||
override fun calculateCashbackPercent() = 0.25f
|
||||
},
|
||||
GOLD("yellow") {
|
||||
override fun getCreditLimit() = 200000
|
||||
override fun calculateCashbackPercent(): Float = 0.5f
|
||||
},
|
||||
PLATINUM("black") {
|
||||
override fun getCreditLimit() = 300000
|
||||
override fun calculateCashbackPercent() = 0.75f
|
||||
};
|
||||
|
||||
companion object {
|
||||
fun getCardTypeByColor(color: String) = values().firstOrNull { it.color == color }
|
||||
fun getCardTypeByName(name: String) = valueOf(name.toUpperCase())
|
||||
}
|
||||
|
||||
abstract fun calculateCashbackPercent(): Float
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.enums
|
||||
|
||||
interface ICardLimit {
|
||||
fun getCreditLimit(): Int
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.inline.classes
|
||||
|
||||
interface Drawable {
|
||||
fun draw()
|
||||
}
|
||||
|
||||
inline class CircleRadius(private val circleRadius : Double) : Drawable {
|
||||
val diameterOfCircle get() = 2 * circleRadius
|
||||
fun areaOfCircle() = 3.14 * circleRadius * circleRadius
|
||||
|
||||
override fun draw() {
|
||||
println("Draw my circle")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.inline.classes
|
||||
|
||||
inline class InlineDoubleWrapper(val doubleValue : Double)
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.interfaces
|
||||
|
||||
interface BaseInterface {
|
||||
fun someMethod(): String
|
||||
}
|
||||
|
||||
interface FirstChildInterface : BaseInterface {
|
||||
override fun someMethod(): String {
|
||||
return("Hello, from someMethod in FirstChildInterface")
|
||||
}
|
||||
}
|
||||
|
||||
interface SecondChildInterface : BaseInterface {
|
||||
override fun someMethod(): String {
|
||||
return("Hello, from someMethod in SecondChildInterface")
|
||||
}
|
||||
}
|
||||
|
||||
class ChildClass : FirstChildInterface, SecondChildInterface {
|
||||
override fun someMethod(): String {
|
||||
return super<SecondChildInterface>.someMethod()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.interfaces
|
||||
|
||||
interface MyInterface {
|
||||
fun someMethod(): String
|
||||
}
|
||||
|
||||
class MyClass() : MyInterface {
|
||||
override fun someMethod(): String {
|
||||
return("Hello, World!")
|
||||
}
|
||||
}
|
||||
|
||||
class MyDerivedClass(myInterface: MyInterface) : MyInterface by myInterface
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.interfaces
|
||||
|
||||
interface FirstInterface {
|
||||
fun someMethod(): String
|
||||
|
||||
fun anotherMethod(): String {
|
||||
return("Hello, from anotherMethod in FirstInterface")
|
||||
}
|
||||
}
|
||||
|
||||
interface SecondInterface {
|
||||
fun someMethod(): String {
|
||||
return("Hello, from someMethod in SecondInterface")
|
||||
}
|
||||
|
||||
fun anotherMethod(): String {
|
||||
return("Hello, from anotherMethod in SecondInterface")
|
||||
}
|
||||
}
|
||||
|
||||
class SomeClass: FirstInterface, SecondInterface {
|
||||
override fun someMethod(): String {
|
||||
return("Hello, from someMethod in SomeClass")
|
||||
}
|
||||
|
||||
override fun anotherMethod(): String {
|
||||
return("Hello, from anotherMethod in SomeClass")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.interfaces
|
||||
|
||||
interface SimpleInterface {
|
||||
val firstProp: String
|
||||
val secondProp: String
|
||||
get() = "Second Property"
|
||||
fun firstMethod(): String
|
||||
fun secondMethod(): String {
|
||||
println("Hello, from: " + secondProp)
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleClass: SimpleInterface {
|
||||
override val firstProp: String = "First Property"
|
||||
override val secondProp: String
|
||||
get() = "Second Property, Overridden!"
|
||||
override fun firstMethod(): String {
|
||||
return("Hello, from: " + firstProp)
|
||||
}
|
||||
override fun secondMethod(): String {
|
||||
return("Hello, from: " + secondProp + firstProp)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom
|
||||
|
||||
class ListExtension {
|
||||
fun <T> List<T>.random(): T? {
|
||||
if (this.isEmpty()) return null
|
||||
return get(ThreadLocalRandom.current().nextInt(count()))
|
||||
}
|
||||
|
||||
fun <T> getRandomElementOfList(list: List<T>): T? {
|
||||
return list.random()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
sealed class Result<out S, out F> {
|
||||
abstract fun <R> map(func: (S) -> R) : Result<R, F>
|
||||
abstract fun <R> mapFailure(func: (F) -> R) : Result<S, R>
|
||||
abstract fun get() : S?
|
||||
}
|
||||
|
||||
data class Success<out S, out F>(val success: S) : Result<S, F>() {
|
||||
override fun <R> map(func: (S) -> R) : Result<R, F> = Success(func(success))
|
||||
override fun <R> mapFailure(func: (F) -> R): Result<S, R> = Success(success)
|
||||
override fun get(): S? = success
|
||||
}
|
||||
|
||||
data class Failure<out S, out F>(val failure: F) : Result<S, F>() {
|
||||
override fun <R> map(func: (S) -> R) : Result<R, F> = Failure(failure)
|
||||
override fun <R> mapFailure(func: (F) -> R): Result<S, R> = Failure(func(failure))
|
||||
override fun get(): S? = null
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
@file:JvmName("Strings")
|
||||
package com.baeldung.kotlin
|
||||
|
||||
fun String.escapeForXml() : String {
|
||||
return this
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.nested
|
||||
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
|
||||
class Computer(val model: String) {
|
||||
|
||||
companion object {
|
||||
const val originCountry = "China"
|
||||
fun getBuiltDate(): String {
|
||||
return "2018-05-23"
|
||||
}
|
||||
|
||||
val log: Logger = LoggerFactory.getLogger(Computer::class.java)
|
||||
}
|
||||
|
||||
//Nested class
|
||||
class MotherBoard(val manufacturer: String) {
|
||||
fun getInfo() = "Made by $manufacturer installed in $originCountry - ${getBuiltDate()}"
|
||||
}
|
||||
|
||||
//Inner class
|
||||
inner class HardDisk(val sizeInGb: Int) {
|
||||
fun getInfo() = "Installed on ${this@Computer} with $sizeInGb GB"
|
||||
}
|
||||
|
||||
interface Switcher {
|
||||
fun on(): String
|
||||
}
|
||||
|
||||
interface Protector {
|
||||
fun smart()
|
||||
}
|
||||
|
||||
fun powerOn(): String {
|
||||
//Local class
|
||||
var defaultColor = "Blue"
|
||||
|
||||
class Led(val color: String) {
|
||||
fun blink(): String {
|
||||
return "blinking $color"
|
||||
}
|
||||
|
||||
fun changeDefaultPowerOnColor() {
|
||||
defaultColor = "Violet"
|
||||
}
|
||||
}
|
||||
|
||||
val powerLed = Led("Green")
|
||||
log.debug("defaultColor is $defaultColor")
|
||||
powerLed.changeDefaultPowerOnColor()
|
||||
log.debug("defaultColor changed inside Led class to $defaultColor")
|
||||
//Anonymous object
|
||||
val powerSwitch = object : Switcher, Protector {
|
||||
override fun on(): String {
|
||||
return powerLed.blink()
|
||||
}
|
||||
|
||||
override fun smart() {
|
||||
log.debug("Smart protection is implemented")
|
||||
}
|
||||
|
||||
fun changeDefaultPowerOnColor() {
|
||||
defaultColor = "Yellow"
|
||||
}
|
||||
}
|
||||
powerSwitch.changeDefaultPowerOnColor()
|
||||
log.debug("defaultColor changed inside powerSwitch anonymous object to $defaultColor")
|
||||
return powerSwitch.on()
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return "Computer(model=$model)"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.static
|
||||
|
||||
class ConsoleUtils {
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun debug(debugMessage : String) {
|
||||
println("[DEBUG] $debugMessage")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.static
|
||||
|
||||
fun debug(debugMessage : String) {
|
||||
println("[DEBUG] $debugMessage")
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.kotlin;
|
||||
|
||||
import kotlin.text.StringsKt;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.baeldung.kotlin.Strings.*;
|
||||
|
||||
|
||||
public class StringUtilUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldEscapeXmlTagsInString() {
|
||||
String xml = "<a>hi</a>";
|
||||
|
||||
String escapedXml = escapeForXml(xml);
|
||||
|
||||
Assert.assertEquals("<a>hi</a>", escapedXml);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingBuiltInKotlinExtensionMethod() {
|
||||
String name = "john";
|
||||
|
||||
String capitalizedName = StringsKt.capitalize(name);
|
||||
|
||||
Assert.assertEquals("John", capitalizedName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.enums
|
||||
|
||||
import org.junit.jupiter.api.Assertions
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
internal class CardTypeUnitTest {
|
||||
|
||||
@Test
|
||||
fun givenSilverCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() {
|
||||
assertEquals(0.25f, CardType.SILVER.calculateCashbackPercent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenGoldCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() {
|
||||
assertEquals(0.5f, CardType.GOLD.calculateCashbackPercent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenPlatinumCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() {
|
||||
assertEquals(0.75f, CardType.PLATINUM.calculateCashbackPercent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenSilverCardType_whenGetCreditLimit_thenReturnCreditLimit() {
|
||||
assertEquals(100000, CardType.SILVER.getCreditLimit())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenGoldCardType_whenGetCreditLimit_thenReturnCreditLimit() {
|
||||
assertEquals(200000, CardType.GOLD.getCreditLimit())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenPlatinumCardType_whenGetCreditLimit_thenReturnCreditLimit() {
|
||||
assertEquals(300000, CardType.PLATINUM.getCreditLimit())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenSilverCardType_whenCheckColor_thenReturnColor() {
|
||||
assertEquals("gray", CardType.SILVER.color)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenGoldCardType_whenCheckColor_thenReturnColor() {
|
||||
assertEquals("yellow", CardType.GOLD.color)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenPlatinumCardType_whenCheckColor_thenReturnColor() {
|
||||
assertEquals("black", CardType.PLATINUM.color)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGetCardTypeByColor_thenSilverCardType() {
|
||||
Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByColor("gray"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGetCardTypeByColor_thenGoldCardType() {
|
||||
Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByColor("yellow"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGetCardTypeByColor_thenPlatinumCardType() {
|
||||
Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByColor("black"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGetCardTypeByName_thenSilverCardType() {
|
||||
Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByName("silver"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGetCardTypeByName_thenGoldCardType() {
|
||||
Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByName("gold"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenGetCardTypeByName_thenPlatinumCardType() {
|
||||
Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByName("platinum"))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.inline.classes
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class CircleRadiusTest {
|
||||
|
||||
@Test
|
||||
fun givenRadius_ThenDiameterIsCorrectlyCalculated() {
|
||||
val radius = CircleRadius(5.0)
|
||||
assertEquals(10.0, radius.diameterOfCircle)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenRadius_ThenAreaIsCorrectlyCalculated() {
|
||||
val radius = CircleRadius(5.0)
|
||||
assertEquals(78.5, radius.areaOfCircle())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.inline.classes
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class InlineDoubleWrapperTest {
|
||||
|
||||
@Test
|
||||
fun whenInclineClassIsUsed_ThenPropertyIsReadCorrectly() {
|
||||
val piDoubleValue = InlineDoubleWrapper(3.14)
|
||||
assertEquals(3.14, piDoubleValue.doubleValue)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.interfaces
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class InterfaceExamplesUnitTest {
|
||||
@Test
|
||||
fun givenAnInterface_whenImplemented_thenBehavesAsOverridden() {
|
||||
val simpleClass = SimpleClass()
|
||||
assertEquals("Hello, from: First Property", simpleClass.firstMethod())
|
||||
assertEquals("Hello, from: Second Property, Overridden!First Property", simpleClass.secondMethod())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenMultipleInterfaces_whenImplemented_thenBehavesAsOverridden() {
|
||||
val someClass = SomeClass()
|
||||
assertEquals("Hello, from someMethod in SomeClass", someClass.someMethod())
|
||||
assertEquals("Hello, from anotherMethod in SomeClass", someClass.anotherMethod())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenConflictingInterfaces_whenImplemented_thenBehavesAsOverridden() {
|
||||
val childClass = ChildClass()
|
||||
assertEquals("Hello, from someMethod in SecondChildInterface", childClass.someMethod())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenAnInterface_whenImplemented_thenBehavesAsDelegated() {
|
||||
val myClass = MyClass()
|
||||
assertEquals("Hello, World!", MyDerivedClass(myClass).someMethod())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class ExtensionMethods {
|
||||
@Test
|
||||
fun simpleExtensionMethod() {
|
||||
Assert.assertEquals("Nothing", "Nothing".escapeForXml())
|
||||
Assert.assertEquals("<Tag>", "<Tag>".escapeForXml())
|
||||
Assert.assertEquals("a&b", "a&b".escapeForXml())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun genericExtensionMethod() {
|
||||
fun <T> T.concatAsString(b: T) : String {
|
||||
return this.toString() + b.toString()
|
||||
}
|
||||
|
||||
Assert.assertEquals("12", "1".concatAsString("2"))
|
||||
Assert.assertEquals("12", 1.concatAsString(2))
|
||||
// This doesn't compile
|
||||
// Assert.assertEquals("12", 1.concatAsString(2.0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun infixExtensionMethod() {
|
||||
infix fun Number.toPowerOf(exponent: Number): Double {
|
||||
return Math.pow(this.toDouble(), exponent.toDouble())
|
||||
}
|
||||
|
||||
Assert.assertEquals(9.0, 3 toPowerOf 2, 0.1)
|
||||
Assert.assertEquals(3.0, 9 toPowerOf 0.5, 0.1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun operatorExtensionMethod() {
|
||||
operator fun List<Int>.times(by: Int): List<Int> {
|
||||
return this.map { it * by }
|
||||
}
|
||||
|
||||
Assert.assertEquals(listOf(2, 4, 6), listOf(1, 2, 3) * 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
import com.baeldung.kotlin.ListExtension
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class ListExtensionTest {
|
||||
@Test
|
||||
fun givenList_whenExecuteExtensionFunctionOnList_shouldReturnRandomElementOfList(){
|
||||
//given
|
||||
val elements = listOf("a", "b", "c")
|
||||
|
||||
//when
|
||||
val result = ListExtension().getRandomElementOfList(elements)
|
||||
|
||||
//then
|
||||
assertTrue(elements.contains(result))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class SealedTest {
|
||||
fun divide(a: Int, b: Int) : Result<Float, String> = when (b) {
|
||||
0 -> Failure("Division by zero")
|
||||
else -> Success(a.toFloat() / b)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSuccess() {
|
||||
val result = divide(10, 5)
|
||||
Assert.assertEquals(Success<Float, String>(2.0f), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testError() {
|
||||
val result = divide(10, 0)
|
||||
Assert.assertEquals(Failure<Float, String>("Division by zero"), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMatchOnSuccess() {
|
||||
val result = divide(10, 5)
|
||||
when (result) {
|
||||
is Success -> {
|
||||
// Expected
|
||||
}
|
||||
is Failure -> Assert.fail("Expected Success")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMatchOnError() {
|
||||
val result = divide(10, 0)
|
||||
when (result) {
|
||||
is Failure -> {
|
||||
// Expected
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetSuccess() {
|
||||
val result = divide(10, 5)
|
||||
Assert.assertEquals(2.0f, result.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testGetError() {
|
||||
val result = divide(10, 0)
|
||||
Assert.assertNull(result.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMapOnSuccess() {
|
||||
val result = divide(10, 5)
|
||||
.map { "Result: $it" }
|
||||
Assert.assertEquals(Success<String, String>("Result: 2.0"), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMapOnError() {
|
||||
val result = divide(10, 0)
|
||||
.map { "Result: $it" }
|
||||
Assert.assertEquals(Failure<Float, String>("Division by zero"), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMapFailureOnSuccess() {
|
||||
val result = divide(10, 5)
|
||||
.mapFailure { "Failure: $it" }
|
||||
Assert.assertEquals(Success<Float, String>(2.0f), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testMapFailureOnError() {
|
||||
val result = divide(10, 0)
|
||||
.mapFailure { "Failure: $it" }
|
||||
Assert.assertEquals(Failure<Float, String>("Failure: Division by zero"), result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
object Counter {
|
||||
private var count: Int = 0
|
||||
|
||||
fun currentCount() = count
|
||||
|
||||
fun increment() {
|
||||
++count
|
||||
}
|
||||
|
||||
fun decrement() {
|
||||
--count
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class ObjectsTest {
|
||||
@Test
|
||||
fun singleton() {
|
||||
|
||||
Assert.assertEquals(42, SimpleSingleton.answer)
|
||||
Assert.assertEquals("Hello, world!", SimpleSingleton.greet("world"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun counter() {
|
||||
Assert.assertEquals(0, Counter.currentCount())
|
||||
Counter.increment()
|
||||
Assert.assertEquals(1, Counter.currentCount())
|
||||
Counter.decrement()
|
||||
Assert.assertEquals(0, Counter.currentCount())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun comparator() {
|
||||
val strings = listOf("Hello", "World")
|
||||
val sortedStrings = strings.sortedWith(ReverseStringComparator)
|
||||
|
||||
Assert.assertEquals(listOf("World", "Hello"), sortedStrings)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun companion() {
|
||||
Assert.assertEquals("You can see me", OuterClass.public)
|
||||
// Assert.assertEquals("You can't see me", OuterClass.secret) // Cannot access 'secret'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
class OuterClass {
|
||||
companion object {
|
||||
private val secret = "You can't see me"
|
||||
val public = "You can see me"
|
||||
}
|
||||
|
||||
fun getSecretValue() = secret
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
object ReverseStringComparator : Comparator<String> {
|
||||
override fun compare(o1: String, o2: String) = o1.reversed().compareTo(o2.reversed())
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
object SimpleSingleton {
|
||||
val answer = 42;
|
||||
|
||||
fun greet(name: String) = "Hello, $name!"
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
class StaticClass {
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val staticField = 42
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.nested
|
||||
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class ComputerUnitTest {
|
||||
|
||||
@Test
|
||||
fun givenComputer_whenPowerOn_thenBlink() {
|
||||
val computer = Computer("Desktop")
|
||||
|
||||
assertThat(computer.powerOn()).isEqualTo("blinking Green")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenMotherboard_whenGetInfo_thenGetInstalledAndBuiltDetails() {
|
||||
val motherBoard = Computer.MotherBoard("MotherBoard Inc.")
|
||||
|
||||
assertThat(motherBoard.getInfo()).isEqualTo("Made by MotherBoard Inc. installed in China - 2018-05-23")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenHardDisk_whenGetInfo_thenGetComputerModelAndDiskSizeInGb() {
|
||||
val hardDisk = Computer("Desktop").HardDisk(1000)
|
||||
|
||||
assertThat(hardDisk.getInfo()).isEqualTo("Installed on Computer(model=Desktop) with 1000 GB")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.static
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
class ConsoleUtilsUnitTest {
|
||||
@Test
|
||||
fun givenAStaticMethod_whenCalled_thenNoErrorIsThrown() {
|
||||
ConsoleUtils.debug("test message")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.static
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
class LoggingUtilsUnitTest {
|
||||
@Test
|
||||
fun givenAPackageMethod_whenCalled_thenNoErrorIsThrown() {
|
||||
debug("test message")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user