Skip to content

Commit fe2b30a

Browse files
authored
Merge pull request #1178 from sk1418/impr-check-type
[impr-check-type] generic type checking
2 parents 7356f86 + 71bf596 commit fe2b30a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

core-kotlin-modules/core-kotlin-lang-3/src/test/kotlin/com/baeldung/typeCheckAndCasts/TypeCheckAndCastsUnitTest.kt

+30
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ fun doubleTheValue(obj: Any): Any =
2121
else -> "Unsupported Type Found"
2222
}
2323

24+
inline fun <reified T> Any.isType() = this is T
25+
inline fun <reified T> Any.isTypedList() = this is List<*> && all { it is T }
26+
2427
class TypeCheckAndSmartCastsUnitTest {
2528
@Test
2629
fun `given type check functions when pass an object should get expected result`() {
@@ -34,6 +37,33 @@ class TypeCheckAndSmartCastsUnitTest {
3437
assertThat(isNotString(aLong)).isTrue
3538
}
3639

40+
@Test
41+
fun `given an object when check type without generic type parameter should get expected exception`() {
42+
val aStringList: Any = listOf("string1", "string2", "string3")
43+
// assertThat(aStringList is List<String>).isTrue() // doesn't compile!!
44+
assertThat(aStringList is List<*>).isTrue
45+
}
46+
47+
@Test
48+
fun `given generic type check functions when check type with isType() should get expected incorrect result`() {
49+
val aStringList: Any = listOf("string1", "string2", "string3")
50+
assertThat(aStringList.isType<List<String>>()).isTrue
51+
52+
val anIntList: Any = listOf(1, 2, 3)
53+
assertThat(anIntList.isType<List<String>>()).isTrue //expect: false
54+
}
55+
56+
@Test
57+
fun `given generic type check functions when check type with type parameters should get expected result`() {
58+
val aStringList: Any = listOf("string1", "string2", "string3")
59+
assertThat(aStringList.isTypedList<String>()).isTrue
60+
61+
62+
val anIntList: Any = listOf(1, 2, 3)
63+
assertThat(anIntList.isTypedList<String>()).isFalse
64+
assertThat(anIntList.isTypedList<Int>()).isTrue
65+
}
66+
3767
@Test
3868
fun `given unsafe cast function when pass an object should get expected result`() {
3969
val aString: Any = "I am a String"

0 commit comments

Comments
 (0)