Examples for BAEL-1169 (#3934)

This commit is contained in:
Graham Cox 2018-04-06 12:08:33 +01:00 committed by KevinGilmore
parent 0c6c5b9286
commit 1b454b7267
6 changed files with 81 additions and 0 deletions

View File

@ -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
}
}

View File

@ -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'
}
}

View File

@ -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
}

View File

@ -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())
}

View File

@ -0,0 +1,7 @@
package com.baeldung.kotlin.objects
object SimpleSingleton {
val answer = 42;
fun greet(name: String) = "Hello, $name!"
}

View File

@ -0,0 +1,8 @@
package com.baeldung.kotlin.objects
class StaticClass {
companion object {
@JvmStatic
val staticField = 42
}
}