enum class Direction {
NORTH,
SOUTH,
EAST,
WEST;
val opposite: Direction //opposite는 Driection의 property
get() = when (this) {
NORTH -> SOUTH
SOUTH -> NORTH
EAST -> WEST
WEST -> EAST
}
fun getOpposite(): Direction {
return when (this) {
NORTH -> SOUTH
SOUTH -> NORTH
EAST -> WEST
WEST -> EAST
}
}
fun printDirection() {
println("Current direction: $this")
}
}
fun main() {
val currentDirection = Direction.NORTH
currentDirection.printDirection()
val oppositeDirection = currentDirection.opposite
println("Opposite direction: $oppositeDirection")
}
중복된 이름 오류가 나는데 val opposite 안에 get() 때문에
fun getOpposite() 이름에서 오류가 난다.
get이 의미가 같기 때문이므로 getOpposite의 이름을 바꿔야함
//[enum class + 조건문 + 함수] 요일 enum class 구현하고 전달받은 요일의 내일을 구하는 함수
//tomorrow 함수 열기
//날짜를 받으면, 다음 상수로 return하는 when절 만들기
//main에서 tomorrow 함수 출력하기
//
enum class Days {
MONDAY,
TUESDAY,
WENDSDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
val tomorrow: Days
get() = when (this) {
MONDAY -> TUESDAY
TUESDAY -> WENDSDAY
WENDSDAY -> THURSDAY
THURSDAY -> FRIDAY
FRIDAY -> SATURDAY
SATURDAY -> SUNDAY
SUNDAY -> MONDAY
}
fun isTomorrow(): Days {
return when (this) {
MONDAY -> TUESDAY
TUESDAY -> WENDSDAY
WENDSDAY -> THURSDAY
THURSDAY -> FRIDAY
FRIDAY -> SATURDAY
SATURDAY -> SUNDAY
SUNDAY -> MONDAY
}
}
fun printToday() {
println("Today is $this")
}
}
fun main() {
val today = Days.FRIDAY
today.printToday()
val tomorrowday = today.tomorrow
println("Tomorrow is $tomorrowday")
}
위 코드 복붙했으니 완성
다 이해가 가는 코드는 아니다.
이해가 안가는 부분만 얘기를 해보면 when 절 부분이다.
변수선언한 tomorrow와 fun isTomorrow가 떨어져있지만 이어져있다. 이 부분을 잘 모르겠다.
그렇다고 isTomorrow 함수를 쓰는 것도 아닌데 메소드tomorrow만으로 when절을 쓸 수 있다.