Skip to content

Commit a1b91a2

Browse files
Merge pull request #796 from husam-e/husam/variable-name
feat(kproperty): How to get a property's name in Kotlin
2 parents fddfe9c + 2eeb162 commit a1b91a2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.baeldung.propertyname
2+
3+
import org.junit.jupiter.api.Assertions
4+
import org.junit.jupiter.api.Test
5+
6+
class PropertyNameUnitTest {
7+
8+
@Test
9+
fun `can get property name of a class's property statically`() {
10+
class MyClass(val age: Int, var name: String, val next: MyClass?)
11+
12+
Assertions.assertEquals("next", MyClass::next.name)
13+
}
14+
15+
@Test
16+
fun `can get property name of an instance's property`() {
17+
class MyClass(val age: Int, var name: String, val next: MyClass?)
18+
val instance = MyClass(5, "test", null)
19+
20+
Assertions.assertEquals("next", instance::next.name)
21+
}
22+
23+
@Test
24+
fun `can get the name of a function`() {
25+
fun isValid(num: Int, name: String): Boolean = num > 0 && name.isNotBlank()
26+
27+
Assertions.assertEquals("isValid", ::isValid.name)
28+
}
29+
}

0 commit comments

Comments
 (0)