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

import java.lang.System.*
import java.time.LocalDate

fun main() {
Expand Down Expand Up @@ -27,6 +28,12 @@ fun main() {

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

val sum = variableAdd(1, 2, 3, 4)
println("1 + 2 + 3 + 4 = $sum")

val ms = measure(::longLoop)
println("longLoop takes $ms milliseconds")
}

infix fun Int.by(other: Int): Int = this * other
Expand Down Expand Up @@ -78,3 +85,41 @@ 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

fun variableAdd(a: Int, b: Int, vararg values: Int): Int {
var result = a + b

for(i in values) {
result += i
}

return result
}

fun sumStrings(vararg strings: String, separator: Char = ' '): String {
var result: String = ""

for(i in strings) {
if(result.isEmpty())
result += i
else
result += ("$separator" + i)
}

return result
}

fun longLoop() {
for(i in 1..100) {
println("i = $i")
Thread.sleep(10)
}
}

fun measure( oper: () -> Unit ): Long {
val start = currentTimeMillis()

oper()

return (currentTimeMillis() - start)
}
12 changes: 12 additions & 0 deletions src/test/kotlin/ru/otus/homework/FunctionsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,16 @@ class FunctionsTest {
calculate(1, 2)
)
}
fun sumStringsTest() {
Assertions.assertEquals(
"str1 str2 str3",
sumStrings("str1", "str2", "str3")
)
}
fun sumStringsTest2() {
Assertions.assertEquals(
"str1,str2,str3",
sumStrings("str1", "str2", "str3", separator = ',')
)
}
}