Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import java.util.concurrent.CompletableFuture
typealias CreditCard = String
fun linkCard(card: CreditCard) {
// omitted
println(card)
}

fun main() {
val cc: CreditCard = "1234****"
linkCard(cc)
val other = cc.toUpperCase()
val other = cc.uppercase()
println("CreditCard uppercase: $other")
linkCard("1234****")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package com.baeldung.staticinit
class Static {

companion object {
lateinit var answer: String
var answer: String

init {
answer = "42"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ fun printStrings(vararg vs: String) {
vs.forEach { println(it) } // Array<String>
}

fun createUser(vararg roles: String, username: String, age: Int) {}
fun createUser(vararg roles: String, username: String, age: Int) {
println("Input params. roles: $roles, username: $username, age: $age")
}

fun main() {
createUser("admin", "user", username = "me", age = 42)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class Book {

val title: String = DEFAULT_TITLE
get() {
return field.toUpperCase()
return field.uppercase()
}

var rating: Int = 5
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ class Person(val firstName: String, val lastName: String) {
}

fun main() {
val p = Person("dehghani")
Person("dehghani")
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class BookUnitTest {
fun `Given a Book instance, When title property is read, Then custom getter is called`() {
val book = Book()

assertEquals(DEFAULT_TITLE.toUpperCase(), book.title)
assertEquals(DEFAULT_TITLE.uppercase(), book.title)
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ val clientExecutor: ExecutorService = Executors.newSingleThreadExecutor()
val image = "CDBmleEGw\"V.\t_1᪉-nm@FiUsQuGҘ*-*bQӘ4?`q;?7y1Z~ᡷ}V=BX!%S>TtecHkmdXhi3".encodeToByteArray()

class HTTPClientStub {
fun get(imageUrl: URL): Response = Response(200) { image }
fun get(imageUrl: URL): Response = Response(200) {
println("Image URL is: $imageUrl")
image
}
fun put(url: String, body: ByteArray) {

println("Input params. URL: $url, body: $body")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ fun unrefactoredFunction(imageUrl: URL, objectId: String) {

val imageData = imageResponse.receive()

val cdnResponse = try {
try {
clientExecutor.submit(Callable { client.put("$CDN_URL/$objectId", imageData) })
.get(10L, TimeUnit.SECONDS)
} catch (ex: Exception) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class RunClass {
}
}

fun main(args: Array<String>) {
fun main() {
println("Running the main function")
RunClass().printInsideClass()
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class VarargSpread {
val listOfStrings = listOf("ab", "cd")
assertTrue { concat(*strings) == "abcd" }
assertTrue { concat2(*strings) == "01abcd" }
assertTrue { concat3(strings = *strings, initialValue = "01") == "01abcd" }
assertTrue { concat3(strings = strings, initialValue = "01") == "01abcd" }
assertTrue { concat(*strings, "ef", *moreStrings) == "abcdefghij" }
assertTrue { concat(*listOfStrings.toTypedArray()) == "abcd" }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.baeldung.evenodd

import org.junit.jupiter.api.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals

class FirstNElementsUnitTest {

Expand Down Expand Up @@ -45,6 +46,8 @@ class FirstNElementsUnitTest {
fun `Convert a list to an array`() {
val list: List<Int> = listOf(1, 2, 3, 4)
val array: Array<Int> = list.toTypedArray()
assertEquals(1, array[0])
assertEquals(2, array[1])
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ fun main() {
println(epoch.monthNumber())
println(epoch.month())

Date.now()
LocalDateTime.now()
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.baeldung.unusedParamter

fun paramInFunction(num: Int, magic: String) {
fun paramInFunction(num: Int) {
println("We only use the Int parameter: $num")
}

Expand All @@ -16,7 +16,7 @@ fun paramInFunction3(num3: Int, magic3: String) {


fun paramInLambda() {
listOf("Kotlin", "Java", "Python").forEachIndexed { idx, value -> println("We only print the of index the element: $idx") }
listOf("Kotlin", "Java", "Python").forEachIndexed { idx, _ -> println("We only print the of index the element: $idx") }
}

fun paramInLambda2() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ParseUrlUnitTest {

@Test
fun `given url when parsed with URL class returns user parameter`() {
val url = URL(urlToParse)
val url = URI(urlToParse).toURL()
val userNameFromUrl = url.findParameterValue("user")
assertThat(userNameFromUrl).isEqualTo("Bob")
assertThat(url.protocol).isEqualTo("https")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.baeldung.runCatchingTryFinally

fun tryToDoSomething(): Int {
var result = 0
var result: Int
val resource = acquireResource()
try {
// Code that can throw an exception
Expand All @@ -24,5 +24,10 @@ fun doSomethingRunCatching(): Int {


fun acquireResource() = Any()
fun releaseResource(any: Any) = Any()
fun performAction(any: Any) = 1
fun releaseResource(any: Any) {
println("Any is: $any")
}
fun performAction(any: Any): Int {
println("Any is: $any")
return 1
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,18 @@ fun basicTryCatch() {
// Handle exception here
val stackTrace = e.stackTrace
// do something with the stackTrace
println("Stack trace: $stackTrace")
}

val result: Result<*> = runCatching {
// Code that might throw an exception
}

result.fold(
onSuccess = { value ->
onSuccess = { _ ->
// Handle the successful execution
},
onFailure = { exception ->
onFailure = { _ ->
// Handle exception here
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,6 @@ data class TitledArticle(private val title: String)
private fun blogSample() {
val blog = Blog<TitledArticle>("Baeldung on Kotlin")
val blogCount = blog.add(TitledArticle("An Introduction to KDoc"))
println("Blog count is: $blogCount")
}

Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package com.baeldung.todo

class Calculator {
fun add(a: Int, b: Int): Int {
println("Input. a= $a and b= $b")
TODO("Implement a + b")
}

fun subtract(a: Int, b: Int): Int {
println("Input. a= $a and b= $b")
TODO("Implement a - b")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class ConvertAnyToIntTest {
fun `when casting to Int then exception is thrown`() {
val anyValue: Any = "Not a number"
assertThrows<ClassCastException> {
val intValue: Int = anyValue as Int
anyValue as Int
}
}

Expand All @@ -27,7 +27,6 @@ class ConvertAnyToIntTest {
val anyValue: Any = "Not a number"
assertThrows<NumberFormatException> {
if (anyValue is Int) {
val intValue: Int = anyValue
} else {
throw NumberFormatException("Provided value is not a number")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,24 @@ package com.baeldung.underscoreoperator
// Before Kotlin 1.7
class Box<T>(value: T) {
// Some class implementation
var a = value
}
fun main() {
val intBox: Box<Int> = Box(42)
println("Int box is: $intBox")
val anyBox: Box<Any> = Box("Some value")
println("Any box is: $anyBox")
}
fun main1(args: Array<String>) {
fun main1() {
val (_, second) = "ignored" to "hello"
println(second)
}
fun mainTwo(args: Array<String>) {
fun mainTwo() {
val list = listOf("hi")
val list2 = list.mapIndexed { _, item -> item }
println(list2)
}
inline fun <T> printElementInfo(element: T) {
fun <T> printElementInfo(element: T) {
println("Element: $element")
}
fun mainForHOF() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ object MathUtils {

object ExtensionUtil {
fun String.isPalindrome(): Boolean {
val cleanString = this.replace("\\s".toRegex(), "").toLowerCase()
val cleanString = this.replace("\\s".toRegex(), "").lowercase()
return cleanString == cleanString.reversed()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fun getDailyRoutine(day: Day): String {
}
}

fun main(args: Array<String>) {
fun main() {
val shape: Shape = Shape.Triangle
when (shape) {
Shape.Square -> println("I'm a square")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.baeldung.callbacktocoroutine

import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlin.coroutines.resume
Expand Down Expand Up @@ -51,17 +52,17 @@ class CallbackToCoroutineExample {
return "processed-data"
}

@OptIn(DelicateCoroutinesApi::class)
fun main() {
val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
val exceptionHandler = CoroutineExceptionHandler { _, _ ->
// Handle exception
}

// Calling the fetchData function within a coroutine scope with an exception handler
GlobalScope.launch(exceptionHandler) {
val result = fetchDataWithCoroutine()
// Handle successful result
print("Result is: $result")
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ class CoroutineExample {
return@withContext "processed-data"
}

@OptIn(DelicateCoroutinesApi::class)
fun main() {
// Calling the fetchData function within a coroutine scope
GlobalScope.launch {
try {
val result = fetchData()
// Handle successful result
println("Result is: $result")
} catch (error: Throwable) {
// Handle error
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ value class Wrapper<T>(val value: T)
fun main() {
val wrapper = Wrapper<Int>(42)
val value: Int = wrapper.value // No runtime overhead
println("Value is: $value")
val list = listOf(42)
val item: Int = list[0] // Boxing and unboxing overhead
println("Item is: $item")
}

@JvmInline
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ fun main() {
val (name, age) = twoPair()
println("$name is $age years old")

val (name2, age2, bornOn) = threeValues()
val (v1, v2, v3, v4, v5) = fiveValues()
val (podName, ip, assignedNode) = getUniquePod()
val (publicKey, privateKey) = getRsaKeyPair()
val (_, _, _) = threeValues()
val (_, _, _, _, _) = fiveValues()
val (_, _, _) = getUniquePod()
val (_, _) = getRsaKeyPair()
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ class CallbackFunctionUnitTest {
}

fun openPDF(bookId: Int){
downloadBook { id ->
downloadBook { _ ->
saveBook(bookId){bookId ->
openBook(bookId)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.baeldung.serialization.defaultValueParameters

import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.Serializable
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString
import kotlinx.serialization.decodeFromString
Expand All @@ -17,7 +18,7 @@ data class Car1(val type: String, val color: String)
data class Car2(val type: String, val color: String = "Blue")

@Serializable
data class Car3(val type: String, @EncodeDefault val color: String = "Blue")
data class Car3 @OptIn(ExperimentalSerializationApi::class) constructor(val type: String, @EncodeDefault val color: String = "Blue")

class DefaultValueSerializationUnitTest {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class ExtensionSubclass : LoggerAsExtensionOnAny()

fun <T : Any> T.logger(): Logger = getLogger(getClassForLogging(javaClass))

fun main(args: Array<String>) {
fun main() {
LoggerAsExtensionOnAny().log("test")
ExtensionSubclass().log("sub")
"foo".logger().info("foo")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ open class LoggerAsExtensionOnMarkerInterface : Logging {

class MarkerExtensionSubclass : LoggerAsExtensionOnMarkerInterface()

fun main(args: Array<String>) {
fun main() {
LoggerAsExtensionOnMarkerInterface().log("test")
MarkerExtensionSubclass().log("sub")
"foo".logger().info("foo")
Expand Down
Loading