๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ

[Kotlin] class / data class / enum class

category Web/Kotlin 2023. 8. 20. 16:24

class์™€ data class์˜ ์ฐจ์ด์ 

=> data class๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ์ž๋™์œผ๋กœ ์ƒ์„ฑ๋œ๋‹ค.

- data class๋Š” ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ์ž๋™์œผ๋กœ getter(), setter(), equals(), hashCode(), toString() ๋ฉ”์†Œ๋“œ๋ฅผ ์ƒ์„ฑํ•ด์ค€๋‹ค.

 

data class๋Š” ์ฃผ๋กœ DTO(Data Transfer Object)๋ฅผ ์œ„ํ•ด ์‚ฌ์šฉ๋œ๋‹ค.

 

fun main() {
    val p1: Person = Person("๊ฐ•์ˆ˜๋‚˜", 20)
    println("Person name is ${p1.name}, age is ${p1.age}")
    
    val p2: Person2 = Person2("๊ฐ•์ˆ˜๋‚˜", 20)
    println("Person name is ${p1.name}, age is ${p1.age}")
}

class Person(val name: String, val age: Int) //์ƒ์„ฑ์ž ๊ธฐ๋ณธ์œผ๋กœ ๋งŒ๋“ค์–ด์ง

data class Person2(val name: String, val age: Int) //์ƒ์„ฑ์ž ๊ธฐ๋ณธ์œผ๋กœ ๋งŒ๋“ค์–ด์ง

/**
 * class์™€ data class์˜ ์ฐจ์ด์ ?
 * 
 * data class๋กœ ๋งŒ๋“ค๋ฉด ๊ธฐ๋ณธ์ ์œผ๋กœ getter, setter, toString, equals, hashCode, component ... ํ•จ์ˆ˜๋“ค์ด ์ž๋™์œผ๋กœ ์ƒ์„ฑ๋จ.
 * setter์˜ ๊ฒฝ์šฐ ๋ฉค๋ฒ„๋ณ€์ˆ˜๋ฅผ val๋กœ ์„ค์ •ํ•˜๋ฉด ์ƒ์„ฑ์ด ์•ˆ๋˜๊ณ , var๋กœ ์„ค์ •ํ•ด์•ผ ์ƒ์„ฑ์ด ๋จ!
 **/

enum class Color {
    RED,	//์ƒ์ˆ˜๊ฐ’
    GREEN,
    BLUE,
}

'Web > Kotlin' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Kotlin] if / when  (0) 2023.08.20
[Kotlin] ? / ?. / ?: / !!.  (0) 2023.08.20
[Kotlin] ๋ณ€์ˆ˜ ์„ ์–ธ ์‹œ var / val ์ฐจ์ด  (0) 2023.08.18