@@ -2,6 +2,7 @@ package com.baeldung.kotlin.anonymousObjects
2
2
3
3
import org.assertj.core.api.Assertions.assertThat
4
4
import org.junit.jupiter.api.Test
5
+ import kotlin.test.assertFailsWith
5
6
6
7
abstract class Doc (val title : String , val author : String , var words : Long = 0L ) {
7
8
abstract fun summary (): String
@@ -16,7 +17,7 @@ interface Printable {
16
17
* If we use an anonymous object as the return value of a private method,
17
18
* its members can still be accessed
18
19
*/
19
- class PlayerService () {
20
+ class PlayerService {
20
21
private fun giveMeAPlayer () = object {
21
22
val name = " Kai"
22
23
val gamePlayed = 6L
@@ -76,9 +77,47 @@ class AnonymousObjectsUnitTest {
76
77
val playerService = PlayerService ()
77
78
assertThat(playerService.getTheName()).isEqualTo(" Kai" )
78
79
}
79
- }
80
80
81
+ @Test
82
+ fun `when anonymous object with a supertype, explict casting isn't required` () {
83
+ fun docTitleToUppercase (doc : Doc ) = doc.title.uppercase()
81
84
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
+ }
82
90
91
+ @Test
92
+ fun `when anonymous object of Any, explict casting doesn't work` () {
83
93
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
+ }
84
102
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