Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions core-kotlin/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.baeldung.kotlin.objects

object Counter {
private var count: Int = 0

fun currentCount() = count

fun increment() {
++count
}

fun decrement() {
--count
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.baeldung.kotlin.objects

import org.junit.Assert
import org.junit.Test

class ObjectsTest {
@Test
fun singleton() {

Assert.assertEquals(42, SimpleSingleton.answer)
Assert.assertEquals("Hello, world!", SimpleSingleton.greet("world"))
}

@Test
fun counter() {
Assert.assertEquals(0, Counter.currentCount())
Counter.increment()
Assert.assertEquals(1, Counter.currentCount())
Counter.decrement()
Assert.assertEquals(0, Counter.currentCount())
}

@Test
fun comparator() {
val strings = listOf("Hello", "World")
val sortedStrings = strings.sortedWith(ReverseStringComparator)

Assert.assertEquals(listOf("World", "Hello"), sortedStrings)
}

@Test
fun companion() {
Assert.assertEquals("You can see me", OuterClass.public)
// Assert.assertEquals("You can't see me", OuterClass.secret) // Cannot access 'secret'
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.baeldung.kotlin.objects

class OuterClass {
companion object {
private val secret = "You can't see me"
val public = "You can see me"
}

fun getSecretValue() = secret
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.baeldung.kotlin.objects

object ReverseStringComparator : Comparator<String> {
override fun compare(o1: String, o2: String) = o1.reversed().compareTo(o2.reversed())
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.baeldung.kotlin.objects

object SimpleSingleton {
val answer = 42;

fun greet(name: String) = "Hello, $name!"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.baeldung.kotlin.objects

class StaticClass {
companion object {
@JvmStatic
val staticField = 42
}
}