Skip to content

Commit 0891a5f

Browse files
authored
Merge pull request #916 from sk1418/anonymous-obj-casting
add type casting
2 parents cde6369 + 0791787 commit 0891a5f

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/anonymousObjects/AnonymousObjectsUnitTest.kt

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package com.baeldung.kotlin.anonymousObjects
22

33
import org.assertj.core.api.Assertions.assertThat
44
import org.junit.jupiter.api.Test
5+
import kotlin.test.assertFailsWith
56

67
abstract class Doc(val title: String, val author: String, var words: Long = 0L) {
78
abstract fun summary(): String
@@ -16,7 +17,7 @@ interface Printable {
1617
* If we use an anonymous object as the return value of a private method,
1718
* its members can still be accessed
1819
*/
19-
class PlayerService() {
20+
class PlayerService {
2021
private fun giveMeAPlayer() = object {
2122
val name = "Kai"
2223
val gamePlayed = 6L
@@ -76,9 +77,47 @@ class AnonymousObjectsUnitTest {
7677
val playerService = PlayerService()
7778
assertThat(playerService.getTheName()).isEqualTo("Kai")
7879
}
79-
}
8080

81+
@Test
82+
fun `when anonymous object with a supertype, explict casting isn't required`() {
83+
fun docTitleToUppercase(doc: Doc) = doc.title.uppercase()
8184

85+
val article = object : Doc(title = "A nice article", author = "Kai", words = 420) {
86+
override fun summary() = "Title: <$title> ($words words) By $author"
87+
}
88+
assertThat(docTitleToUppercase(article)).isEqualTo("A NICE ARTICLE")
89+
}
8290

91+
@Test
92+
fun `when anonymous object of Any, explict casting doesn't work`() {
8393

94+
// the class
95+
data class Player(
96+
val name: String,
97+
val gamePlayed: Long,
98+
val points: Long
99+
) {
100+
fun pointsPerGame() = "$name: AVG points per Game: ${points / gamePlayed}"
101+
}
84102

103+
// the anonymous object
104+
val anonymousPlayer = object {
105+
val name = "Kai"
106+
val gamePlayed = 6L
107+
val points = 42L
108+
fun pointsPerGame() = "$name: AVG points per Game: ${points / gamePlayed}"
109+
}
110+
111+
assertFailsWith<ClassCastException> { anonymousPlayer as Player }
112+
113+
val alwaysNull = anonymousPlayer as? Player
114+
assertThat(alwaysNull).isNull()
115+
116+
val realPlayer = Player(name = "Liam", gamePlayed = 7L, points = 77L)
117+
118+
// Kotlin doesn't support duck typing, the below code doesn't compile:
119+
// val stringList = listOf(realPlayer, anonymousPlayer).map{
120+
// it.pointsPerGame()
121+
// }
122+
}
123+
}

0 commit comments

Comments
 (0)