This commit is contained in:
@@ -1,17 +0,0 @@
|
||||
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")
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.baeldung.constructor
|
||||
|
||||
class Employee(name: String, val salary: Int): Person(name)
|
||||
@@ -1,19 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
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 + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.baeldung.dataclass
|
||||
|
||||
data class Movie(val name: String, val studio: String, var rating: Float)
|
||||
@@ -1,26 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.enums
|
||||
|
||||
interface ICardLimit {
|
||||
fun getCreditLimit(): Int
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
inline fun <reified T> Iterable<*>.filterIsInstance() = filter { it is T }
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val set = setOf("1984", 2, 3, "Brave new world", 11)
|
||||
println(set.filterIsInstance<Int>())
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
package com.baeldung.inline.classes
|
||||
|
||||
inline class InlineDoubleWrapper(val doubleValue : Double)
|
||||
@@ -1,23 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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
|
||||
@@ -1,29 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
@file:JvmName("Strings")
|
||||
package com.baeldung.kotlin
|
||||
|
||||
fun String.escapeForXml() : String {
|
||||
return this
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.kotlin.delegates
|
||||
|
||||
val data = arrayOf<MutableMap<String, Any?>>(
|
||||
mutableMapOf(
|
||||
"id" to 1,
|
||||
"name" to "George",
|
||||
"age" to 4
|
||||
),
|
||||
mutableMapOf(
|
||||
"id" to 2,
|
||||
"name" to "Charlotte",
|
||||
"age" to 2
|
||||
)
|
||||
)
|
||||
|
||||
class NoRecordFoundException(id: Int) : Exception("No record found for id $id") {
|
||||
init {
|
||||
println("No record found for ID $id")
|
||||
}
|
||||
}
|
||||
|
||||
fun queryForValue(field: String, id: Int): Any {
|
||||
println("Loading record $id from the fake database")
|
||||
val value = data.firstOrNull { it["id"] == id }
|
||||
?.get(field) ?: throw NoRecordFoundException(id)
|
||||
println("Loaded value $value for field $field of record $id")
|
||||
return value
|
||||
}
|
||||
|
||||
fun update(field: String, id: Int, value: Any?) {
|
||||
println("Updating field $field of record $id to value $value in the fake database")
|
||||
data.firstOrNull { it["id"] == id }
|
||||
?.put(field, value)
|
||||
?: throw NoRecordFoundException(id)
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.baeldung.kotlin.delegates
|
||||
|
||||
import kotlin.properties.ReadWriteProperty
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
class DatabaseDelegate<in R, T>(private val field: String, private val id: Int) : ReadWriteProperty<R, T> {
|
||||
override fun getValue(thisRef: R, property: KProperty<*>): T =
|
||||
queryForValue(field, id) as T
|
||||
|
||||
override fun setValue(thisRef: R, property: KProperty<*>, value: T) {
|
||||
update(field, id, value)
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package com.baeldung.kotlin.delegates
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
interface Producer {
|
||||
|
||||
fun produce(): String
|
||||
}
|
||||
|
||||
class ProducerImpl : Producer {
|
||||
|
||||
override fun produce() = "ProducerImpl"
|
||||
}
|
||||
|
||||
class EnhancedProducer(private val delegate: Producer) : Producer by delegate {
|
||||
|
||||
override fun produce() = "${delegate.produce()} and EnhancedProducer"
|
||||
}
|
||||
|
||||
interface MessageService {
|
||||
|
||||
fun processMessage(message: String): String
|
||||
}
|
||||
|
||||
class MessageServiceImpl : MessageService {
|
||||
override fun processMessage(message: String): String {
|
||||
return "MessageServiceImpl: $message"
|
||||
}
|
||||
}
|
||||
|
||||
interface UserService {
|
||||
|
||||
fun processUser(userId: String): String
|
||||
}
|
||||
|
||||
class UserServiceImpl : UserService {
|
||||
|
||||
override fun processUser(userId: String): String {
|
||||
return "UserServiceImpl: $userId"
|
||||
}
|
||||
}
|
||||
|
||||
class CompositeService : UserService by UserServiceImpl(), MessageService by MessageServiceImpl()
|
||||
|
||||
interface Service {
|
||||
|
||||
val seed: Int
|
||||
|
||||
fun serve(action: (Int) -> Unit)
|
||||
}
|
||||
|
||||
class ServiceImpl : Service {
|
||||
|
||||
override val seed = 1
|
||||
|
||||
override fun serve(action: (Int) -> Unit) {
|
||||
action(seed)
|
||||
}
|
||||
}
|
||||
|
||||
class ServiceDecorator : Service by ServiceImpl() {
|
||||
override val seed = 2
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.baeldung.kotlin.delegates
|
||||
|
||||
class User(val id: Int) {
|
||||
var name: String by DatabaseDelegate("name", id)
|
||||
var age: Int by DatabaseDelegate("age", id)
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
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)"
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.static
|
||||
|
||||
class ConsoleUtils {
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun debug(debugMessage : String) {
|
||||
println("[DEBUG] $debugMessage")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.static
|
||||
|
||||
fun debug(debugMessage : String) {
|
||||
println("[DEBUG] $debugMessage")
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
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"))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class GenericsTest {
|
||||
|
||||
@Test
|
||||
fun givenParametrizeClass_whenInitializeItWithSpecificType_thenShouldBeParameterized() {
|
||||
//given
|
||||
val parameterizedClass = ParameterizedClass<String>("string-value")
|
||||
|
||||
//when
|
||||
val res = parameterizedClass.getValue()
|
||||
|
||||
//then
|
||||
assertTrue(res is String)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenParametrizeClass_whenInitializeIt_thenShouldBeParameterizedByInferredType() {
|
||||
//given
|
||||
val parameterizedClass = ParameterizedClass("string-value")
|
||||
|
||||
//when
|
||||
val res = parameterizedClass.getValue()
|
||||
|
||||
//then
|
||||
assertTrue(res is String)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenParameterizedProducerByOutKeyword_whenGetValue_thenCanAssignItToSuperType() {
|
||||
//given
|
||||
val parameterizedProducer = ParameterizedProducer("string")
|
||||
|
||||
//when
|
||||
val ref: ParameterizedProducer<Any> = parameterizedProducer
|
||||
|
||||
//then
|
||||
assertTrue(ref is ParameterizedProducer<Any>)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenParameterizedConsumerByInKeyword_whenGetValue_thenCanAssignItToSubType() {
|
||||
//given
|
||||
val parameterizedConsumer = ParameterizedConsumer<Number>()
|
||||
|
||||
//when
|
||||
val ref: ParameterizedConsumer<Double> = parameterizedConsumer
|
||||
|
||||
//then
|
||||
assertTrue(ref is ParameterizedConsumer<Double>)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenTypeProjections_whenOperateOnTwoList_thenCanAcceptListOfSubtypes() {
|
||||
//given
|
||||
val ints: Array<Int> = arrayOf(1, 2, 3)
|
||||
val any: Array<Any?> = arrayOfNulls(3)
|
||||
|
||||
//when
|
||||
copy(ints, any)
|
||||
|
||||
//then
|
||||
assertEquals(any[0], 1)
|
||||
assertEquals(any[1], 2)
|
||||
assertEquals(any[2], 3)
|
||||
|
||||
}
|
||||
|
||||
fun copy(from: Array<out Any>, to: Array<Any?>) {
|
||||
assert(from.size == to.size)
|
||||
for (i in from.indices)
|
||||
to[i] = from[i]
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenTypeProjection_whenHaveArrayOfIn_thenShouldAddElementsOfSubtypesToIt() {
|
||||
//given
|
||||
val objects: Array<Any?> = arrayOfNulls(1)
|
||||
|
||||
//when
|
||||
fill(objects, 1)
|
||||
|
||||
//then
|
||||
assertEquals(objects[0], 1)
|
||||
}
|
||||
|
||||
fun fill(dest: Array<in Int>, value: Int) {
|
||||
dest[0] = value
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenStartProjection_whenPassAnyType_thenCompile() {
|
||||
//given
|
||||
val array = arrayOf(1,2,3)
|
||||
|
||||
//then
|
||||
printArray(array)
|
||||
|
||||
}
|
||||
|
||||
fun printArray(array: Array<*>) {
|
||||
array.forEach { println(it) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenFunctionWithDefinedGenericConstraints_whenCallWithProperType_thenCompile(){
|
||||
//given
|
||||
val listOfInts = listOf(5,2,3,4,1)
|
||||
|
||||
//when
|
||||
val sorted = sort(listOfInts)
|
||||
|
||||
//then
|
||||
assertEquals(sorted, listOf(1,2,3,4,5))
|
||||
}
|
||||
|
||||
fun <T: Comparable<T>> sort(list: List<T>): List<T>{
|
||||
return list.sorted()
|
||||
}
|
||||
|
||||
class ParameterizedClass<A>(private val value: A) {
|
||||
|
||||
fun getValue(): A {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
class ParameterizedProducer<out T>(private val value: T) {
|
||||
fun get(): T {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
class ParameterizedConsumer<in T> {
|
||||
fun toString(value: T): String {
|
||||
return value.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.kotlin.delegates
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class DatabaseDelegatesTest {
|
||||
@Test
|
||||
fun testGetKnownFields() {
|
||||
val user = User(1)
|
||||
assertEquals("George", user.name)
|
||||
assertEquals(4, user.age)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testSetKnownFields() {
|
||||
val user = User(2)
|
||||
user.age = 3
|
||||
assertEquals(3, user.age)
|
||||
}
|
||||
|
||||
@Test(expected = NoRecordFoundException::class)
|
||||
fun testGetKnownField() {
|
||||
val user = User(3)
|
||||
user.name
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.baeldung.kotlin.delegates
|
||||
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.Test
|
||||
|
||||
class InterfaceDelegationTest {
|
||||
|
||||
@Test
|
||||
fun `when delegated implementation is used then it works as expected`() {
|
||||
val producer = EnhancedProducer(ProducerImpl())
|
||||
assertThat(producer.produce()).isEqualTo("ProducerImpl and EnhancedProducer")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `when composite delegation is used then it works as expected`() {
|
||||
val service = CompositeService()
|
||||
assertThat(service.processMessage("message")).isEqualTo("MessageServiceImpl: message")
|
||||
assertThat(service.processUser("user")).isEqualTo("UserServiceImpl: user")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `when decoration is used then delegate knows nothing about it`() {
|
||||
val service = ServiceDecorator()
|
||||
service.serve {
|
||||
assertThat(it).isEqualTo(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
object Counter {
|
||||
private var count: Int = 0
|
||||
|
||||
fun currentCount() = count
|
||||
|
||||
fun increment() {
|
||||
++count
|
||||
}
|
||||
|
||||
fun decrement() {
|
||||
--count
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
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'
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
object ReverseStringComparator : Comparator<String> {
|
||||
override fun compare(o1: String, o2: String) = o1.reversed().compareTo(o2.reversed())
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
object SimpleSingleton {
|
||||
val answer = 42;
|
||||
|
||||
fun greet(name: String) = "Hello, $name!"
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
class StaticClass {
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val staticField = 42
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.static
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
class ConsoleUtilsUnitTest {
|
||||
@Test
|
||||
fun givenAStaticMethod_whenCalled_thenNoErrorIsThrown() {
|
||||
ConsoleUtils.debug("test message")
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
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