Skip to content

Commit 1b454b7

Browse files
sazzerKevinGilmore
authored andcommitted
Examples for BAEL-1169 (eugenp#3934)
1 parent 0c6c5b9 commit 1b454b7

6 files changed

Lines changed: 81 additions & 0 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baeldung.kotlin.objects
2+
3+
object Counter {
4+
private var count: Int = 0
5+
6+
fun currentCount() = count
7+
8+
fun increment() {
9+
++count
10+
}
11+
12+
fun decrement() {
13+
--count
14+
}
15+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.baeldung.kotlin.objects
2+
3+
import org.junit.Assert
4+
import org.junit.Test
5+
6+
class ObjectsTest {
7+
@Test
8+
fun singleton() {
9+
10+
Assert.assertEquals(42, SimpleSingleton.answer)
11+
Assert.assertEquals("Hello, world!", SimpleSingleton.greet("world"))
12+
}
13+
14+
@Test
15+
fun counter() {
16+
Assert.assertEquals(0, Counter.currentCount())
17+
Counter.increment()
18+
Assert.assertEquals(1, Counter.currentCount())
19+
Counter.decrement()
20+
Assert.assertEquals(0, Counter.currentCount())
21+
}
22+
23+
@Test
24+
fun comparator() {
25+
val strings = listOf("Hello", "World")
26+
val sortedStrings = strings.sortedWith(ReverseStringComparator)
27+
28+
Assert.assertEquals(listOf("World", "Hello"), sortedStrings)
29+
}
30+
31+
@Test
32+
fun companion() {
33+
Assert.assertEquals("You can see me", OuterClass.public)
34+
// Assert.assertEquals("You can't see me", OuterClass.secret) // Cannot access 'secret'
35+
}
36+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.baeldung.kotlin.objects
2+
3+
class OuterClass {
4+
companion object {
5+
private val secret = "You can't see me"
6+
val public = "You can see me"
7+
}
8+
9+
fun getSecretValue() = secret
10+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package com.baeldung.kotlin.objects
2+
3+
object ReverseStringComparator : Comparator<String> {
4+
override fun compare(o1: String, o2: String) = o1.reversed().compareTo(o2.reversed())
5+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.baeldung.kotlin.objects
2+
3+
object SimpleSingleton {
4+
val answer = 42;
5+
6+
fun greet(name: String) = "Hello, $name!"
7+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.baeldung.kotlin.objects
2+
3+
class StaticClass {
4+
companion object {
5+
@JvmStatic
6+
val staticField = 42
7+
}
8+
}

0 commit comments

Comments
 (0)