Skip to content
Open
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
28 changes: 28 additions & 0 deletions src/main/kotlin/ru/otus/homework/functions.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ru.otus.homework

import java.time.LocalDate
import kotlin.random.Random

fun main() {
println(calculate(10, 20))
Expand All @@ -27,6 +28,13 @@ fun main() {

val product = 2 by 2
println("Произведение: $product")

println("Время выполнения функции sumOfValues = ${funExecTime {
sumOfValues(1, 2, 3, 4, 5)
}} ms")
println("Время выполнения вынкции concatWithSep = ${funExecTime {
concatWithSep("str1", "str2", "str3", c = ',')
}} ms")
}

infix fun Int.by(other: Int): Int = this * other
Expand Down Expand Up @@ -78,3 +86,23 @@ fun calculate(n1: Int, n2: Int, op: (Int, Int) -> Int): String {

fun add(a: Int, b: Int): Int = a + b
fun subtract(a: Int, b: Int): Int = a - b

// Домашка тут

// ## 1. Функция с обязательными и необязательными позиционными параметрами
// Используем "Элвис" оператор
fun sumOfValues(n1: Int? = null, n2: Int? = null, vararg n: Int) =
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dbulygin , мне кажется, вы не совсем правильно поняли задание:

программа не должна собираться (ошибка компиляции).

В вашем случае, ошибка выскакивает на этапе исполнения (runtime).
Достаточно было сделать вот такую функцию:

fun sumOfValues(n1: Int, n2: Int, vararg n: Int): Int

Тогда, при попытке вызвать ее как-нибудь так: sumOfValues(1) вы бы даже не смогли запустить приложение и отловили ошибку до того, как оно попало к пользователю. В этом и есть польза типизированного языка.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Приветствую! Я понял, был не внимателен, увлёкся процессом, не вчитавшись в задание.
Спасибо за комментарий.

(n1 ?: throw IllegalArgumentException()) +
(n2 ?: throw IllegalArgumentException()) +
n.sum()

// ## 2. Функция с необязательным параметром и позиционными параметрами
fun concatWithSep(vararg s: String, c: Char = ' ') = s.joinToString("$c")

// ## 4. Функция, измеряющая время выполнения другой функции
fun funExecTime(f: () -> Unit): Long {
val start = System.currentTimeMillis()
f()
Thread.sleep(Random.nextLong(200, 1000)) // имитация долгой операции
return System.currentTimeMillis() - start
}
31 changes: 31 additions & 0 deletions src/test/kotlin/ru/otus/homework/FunctionsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ru.otus.homework

import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

class FunctionsTest {
@Test
Expand All @@ -11,4 +12,34 @@ class FunctionsTest {
calculate(1, 2)
)
}
@Test
fun `test of sumOfValues with OK result`() {
Assertions.assertEquals(
15,
sumOfValues(1, 2, 3, 4, 5)
)
}

@Test
fun `test of sumOfValues with throw exceptions result`() {
assertThrows<IllegalArgumentException> {
sumOfValues(1)
}
}

@Test
fun `test of concatWithSep with NON separator`() {
Assertions.assertEquals(
"str1 str2 str3",
concatWithSep("str1", "str2", "str3")
)
}

@Test
fun `test of concatWithSep with separator`() {
Assertions.assertEquals(
"str1,str2,str3",
concatWithSep("str1", "str2", "str3", c=',')
)
}
}