Skip to content

Commit 4dc33ad

Browse files
[KTLN-501] Accessing Methods Outside Companion Object in Kotlin (#817)
* code refactor * code fixes
1 parent 554b209 commit 4dc33ad

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package com.baeldung.methodAccessInCompanionObject
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
6+
class MethodAccessInCompanionObjectUnitTest {
7+
@Test
8+
fun `calls outer method using reference to outer class`() {
9+
val result = OuterClass.companionMethod()
10+
11+
assertEquals("This is a method outside the companion object", result)
12+
}
13+
14+
@Test
15+
fun `calls outer method using interface`() {
16+
val myClass = OuterClassWithInterface()
17+
val result = OuterClassWithInterface.companionMethod(myClass)
18+
19+
assertEquals("This is a method outside the companion object", result)
20+
}
21+
22+
@Test
23+
fun `calls outer method using object declaration`() {
24+
val result = ClassWithObject.companionMethod()
25+
26+
assertEquals("This is a method outside the companion object", result)
27+
}
28+
29+
@Test
30+
fun `calls outer method using function reference`() {
31+
val myClass = ClassWithFunctionReference()
32+
val result = ClassWithFunctionReference.companionMethod(myClass::outerClassMethod)
33+
34+
assertEquals("This is a method outside the companion object", result)
35+
}
36+
}
37+
38+
class OuterClass {
39+
companion object {
40+
val outerClass: OuterClass = OuterClass()
41+
fun companionMethod(): String {
42+
return outerClass.outerClassMethod()
43+
}
44+
}
45+
46+
fun outerClassMethod(): String {
47+
return "This is a method outside the companion object"
48+
}
49+
}
50+
interface OuterClassInterface {
51+
fun outerClassMethod(): String
52+
}
53+
54+
class OuterClassWithInterface : OuterClassInterface {
55+
companion object {
56+
fun companionMethod(outerClassInterface: OuterClassInterface): String {
57+
return outerClassInterface.outerClassMethod()
58+
}
59+
}
60+
61+
override fun outerClassMethod(): String {
62+
return "This is a method outside the companion object"
63+
}
64+
}
65+
class ClassWithObject {
66+
companion object {
67+
fun companionMethod(): String {
68+
return ObjectClass.outerClassMethod()
69+
}
70+
}
71+
72+
object ObjectClass {
73+
fun outerClassMethod(): String {
74+
return "This is a method outside the companion object"
75+
}
76+
}
77+
}
78+
79+
class ClassWithFunctionReference {
80+
companion object {
81+
fun companionMethod(outerClassMethod: () -> String): String {
82+
return outerClassMethod()
83+
}
84+
}
85+
86+
fun outerClassMethod(): String {
87+
return "This is a method outside the companion object"
88+
}
89+
}

0 commit comments

Comments
 (0)