Skip to content

Commit 554b209

Browse files
authored
Merge pull request #818 from sk1418/private-constructor
[private-constructor] private constructor
2 parents bf44688 + 294e218 commit 554b209

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.baeldung.privateConstructor
2+
3+
import org.junit.jupiter.api.Test
4+
import kotlin.test.assertEquals
5+
6+
class Student private constructor(val name: String, val age: Int) {
7+
8+
companion object {
9+
fun createInstance(pair: Pair<String, Int>): Student {
10+
return Student(pair.first.uppercase(), pair.second)
11+
}
12+
}
13+
}
14+
15+
data class StudentData private constructor(val name: String, val age: Int) {
16+
17+
companion object {
18+
fun createInstance(pair: Pair<String, Int>): StudentData {
19+
return StudentData(pair.first.uppercase(), pair.second)
20+
}
21+
}
22+
}
23+
24+
class PrivateConstructorUnitTest {
25+
@Test
26+
fun `when using private constructor then instance can only be created via companion function`() {
27+
// val kai = Student("Kai", 18)
28+
// Kotlin: Cannot access '<init>': it is private in 'Student'
29+
30+
val kai = Student.createInstance("Kai" to 18)
31+
32+
assertEquals("KAI", kai.name)
33+
assertEquals(18, kai.age)
34+
}
35+
36+
@Test
37+
fun `when using private constructor in data class then copy() exposes the private constructor`() {
38+
// val kaiData = StudentData("Kai", 18)
39+
// Kotlin: Cannot access '<init>': it is private in 'StudentData'
40+
41+
val kaiData = StudentData.createInstance("Kai" to 18)
42+
assertEquals("KAI", kaiData.name)
43+
assertEquals(18, kaiData.age)
44+
45+
val liam = kaiData.copy(name = "Liam", age = 20)
46+
assertEquals("Liam", liam.name)
47+
assertEquals(20, liam.age)
48+
}
49+
}

0 commit comments

Comments
 (0)