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