Skip to content

Commit c238db1

Browse files
KTLN-832 Removing Ambiguity in Kotlin Function by Reference (#1186)
* added unit tests * code changes * code fixes * code fixes * code changes * code changes
1 parent 32ce570 commit c238db1

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package com.baeldung.removeAmbiguityInKotlinFunctionByReference
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
6+
7+
typealias StringComputer = (String) -> String
8+
9+
typealias IntComputer = (Int) -> Int
10+
11+
class Calculator(val base: Int) {
12+
fun compute(value: Int): Int = base + value
13+
fun compute(value: String): String = "$base$value"
14+
}
15+
16+
fun Calculator.computeInt(value: Int): Int = compute(value)
17+
18+
fun Calculator.computeString(value: String): String = compute(value)
19+
20+
class RemoveAmbiguityInKotlinFunctionByReferenceUnitTest {
21+
22+
private val calculator = Calculator(10)
23+
24+
@Test
25+
fun `Should compute with int function`() {
26+
val computeInt: (Int) -> Int = calculator::compute
27+
assertEquals(15, computeInt(5))
28+
}
29+
30+
@Test
31+
fun `Should compute with string function`() {
32+
val computeString: (String) -> String = calculator::compute
33+
assertEquals("105", computeString("5"))
34+
}
35+
36+
@Test
37+
fun `Should compute int with lambda`() {
38+
val computeInt = { value: Int -> calculator.compute(value) }
39+
assertEquals(15, computeInt(5))
40+
}
41+
42+
@Test
43+
fun `Should compute string with lambda`() {
44+
val computeString = { value: String -> calculator.compute(value) }
45+
assertEquals("105", computeString("5"))
46+
}
47+
48+
@Test
49+
fun `should compute int with extension function`() {
50+
val computeIntFn = calculator::computeInt
51+
assertEquals(15, computeIntFn(5))
52+
}
53+
54+
@Test
55+
fun `should compute string with extension function`() {
56+
val computeStringFn = calculator::computeString
57+
assertEquals("105", computeStringFn("5"))
58+
}
59+
60+
61+
@Test
62+
fun `Should compute int with type alias`() {
63+
val computeInt: IntComputer = calculator::compute
64+
assertEquals(15, computeInt(5))
65+
}
66+
67+
@Test
68+
fun `Should compute string with type alias`() {
69+
val computeString: StringComputer = calculator::compute
70+
assertEquals("105", computeString("5"))
71+
}
72+
}

0 commit comments

Comments
 (0)