Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KTLN-832 Removing Ambiguity in Kotlin Function by Reference #1186

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
@@ -0,0 +1,71 @@
package com.baeldung.removeAmbiguityInKotlinFunctionByReference

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


typealias StringComputer = (String) -> String

typealias IntComputer = (Int) -> Int

class RemoveAmbiguityInKotlinFunctionByReferenceUnitTest {
class Calculator(val base: Int) {
fun compute(value: Int): Int = base + value
fun compute(value: String): String = "$base$value"
}

fun Calculator.computeInt(value: Int): Int = compute(value)

fun Calculator.computeString(value: String): String = compute(value)

private val calculator = Calculator(10)

@Test
fun `Should compute with int function`() {
val computeInt: (Int) -> Int = calculator::compute
assertEquals(15, computeInt(5))
}

@Test
fun `Should compute with string function`() {
val computeString: (String) -> String = calculator::compute
assertEquals("105", computeString("5"))
}

@Test
fun `Should compute int with lambda`() {
val computeInt = { value: Int -> calculator.compute(value) }
assertEquals(15, computeInt(5))
}

@Test
fun `Should compute string with lambda`() {
val computeString = { value: String -> calculator.compute(value) }
assertEquals("105", computeString("5"))
}

@Test
fun `should compute int with extension function`() {
val computeInt = calculator.computeInt(5)
assertEquals(15, computeInt)
}

@Test
fun `should compute string with extension function`() {
val computeString = calculator.computeString("5")
assertEquals("105", computeString)
}


@Test
fun `Should compute int with type alias`() {
val computeInt: IntComputer = calculator::compute
assertEquals(15, computeInt(5))
}

@Test
fun `Should compute string with type alias`() {
val computeString: StringComputer = calculator::compute
assertEquals("105", computeString("5"))
}
}