forked from Suryakant-Bharti/Important-Java-Concepts
-
Notifications
You must be signed in to change notification settings - Fork 17
/
State.kt
56 lines (41 loc) Β· 1.47 KB
/
State.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
sealed class AuthorizationState
object Unauthorized : AuthorizationState()
class Authorized(val userName: String) : AuthorizationState()
class AuthorizationPresenter {
private var state: AuthorizationState = Unauthorized
val isAuthorized: Boolean
get() = when (state) {
is Authorized -> true
is Unauthorized -> false
}
val userName: String
get() {
return when (val state = this.state) { //val enables smart casting of state
is Authorized -> state.userName
is Unauthorized -> "Unknown"
}
}
fun loginUser(userName: String) {
state = Authorized(userName)
}
fun logoutUser() {
state = Unauthorized
}
override fun toString() = "User '$userName' is logged in: $isAuthorized"
}
class StateTest {
@Test
fun State() {
val authorizationPresenter = AuthorizationPresenter()
authorizationPresenter.loginUser("admin")
println(authorizationPresenter)
assertThat(authorizationPresenter.isAuthorized).isEqualTo(true)
assertThat(authorizationPresenter.userName).isEqualTo("admin")
authorizationPresenter.logoutUser()
println(authorizationPresenter)
assertThat(authorizationPresenter.isAuthorized).isEqualTo(false)
assertThat(authorizationPresenter.userName).isEqualTo("Unknown")
}
}