Skip to content

Commit 789bf0a

Browse files
[KTLN-512] Passing a Type to Generic Method in Kotlin (#904)
* added unit tests * code fixes * fixed unit tests * fixed unit tests * fixed unit tests
1 parent 378f7e9 commit 789bf0a

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.baeldung.passTypeToGenericMethod
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
6+
class PassTypeToGenericMethod {
7+
@Test
8+
fun `pass type to generic method using reified parameters`() {
9+
10+
assertEquals("String", passTypeUsingReifiedParameter<String>())
11+
assertEquals("Int", passTypeUsingReifiedParameter<Int>())
12+
}
13+
14+
@Test
15+
fun `pass type to generic method using class parameters`() {
16+
17+
assertEquals("String", passTypeUsingClassParameter(String::class.java))
18+
assertEquals("int", passTypeUsingClassParameter(Int::class.java))
19+
}
20+
21+
@Test
22+
fun `pass type to generic method using higher order functions`() {
23+
val intValue = passTypeUsingHigherOrderFunction{42}
24+
val stringValue = passTypeUsingHigherOrderFunction{"Generic Method!"}
25+
26+
assertEquals(42, intValue)
27+
assertEquals("Generic Method!", stringValue)
28+
}
29+
30+
@Test
31+
fun `pass type to generic method using type casting`() {
32+
val intValue = passTypeUsingTypeCasting(0)
33+
val stringValue = passTypeUsingTypeCasting("")
34+
35+
assertEquals(42, intValue)
36+
assertEquals("Generic Method!", stringValue)
37+
}
38+
}
39+
40+
inline fun <reified T> passTypeUsingReifiedParameter(): String? {
41+
return T::class.simpleName
42+
}
43+
44+
fun <T> passTypeUsingClassParameter(clazz: Class<T>): String {
45+
return clazz.simpleName
46+
}
47+
48+
fun <T> passTypeUsingTypeCasting(type: T): T {
49+
return when (type) {
50+
is Int -> 42 as T
51+
is String -> "Generic Method!" as T
52+
else -> throw IllegalArgumentException("Unsupported type")
53+
}
54+
}
55+
56+
fun <T> passTypeUsingHigherOrderFunction(action: () -> T): T {
57+
return action()
58+
}

0 commit comments

Comments
 (0)