๊ด€๋ฆฌ ๋ฉ”๋‰ด

Vintage appMaker์˜ Tech Blog

[kotlin] sealed class์™€ ๋„์ฒดํฌ๋ฅผ ์œ„ํ•œ Elvis ์—ฐ์‚ฐ์ž ๋ณธ๋ฌธ

Source code or Tip/Android(Java, Kotlin)

[kotlin] sealed class์™€ ๋„์ฒดํฌ๋ฅผ ์œ„ํ•œ Elvis ์—ฐ์‚ฐ์ž

VintageappMaker 2021. 1. 6. 12:22

๐Ÿคœ sealed class๋Š” "๋‹ค์–‘ํ•œ ๋ฐ์ดํ„ฐํ˜•์˜ ์ž๋ฃŒ๋ฅผ ํ•œ ๊ฐœ์˜ list๋กœ ๊ด€๋ฆฌํ•ด์•ผํ•  ๋•Œ" ์“ธ๋ชจ์žˆ๋Š” ๋ฐ์ดํ„ฐ ํ˜•์ด๋‹ค. ๊ฐ ๋ฐ์ดํ„ฐํ˜•์€ sealed class๋ฅผ ์ƒ์†๋ฐ›์œผ๋ฉด ๋œ๋‹ค. ์ด ์ž๋ฃŒํ˜•์ด Android์—์„œ ์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” ๊ณณ์€ ๋ฆฌ์‚ฌ์ดํด๋Ÿฌ ๋ทฐ์ด๋‹ค. ํ•œ ๋ฆฌ์ŠคํŠธ์—์„œ ํƒ€์ž…์— ๋”ฐ๋ผ ๋‹ค์–‘ํ•œ ํ™”๋ฉด์„ ๋ณด์—ฌ์ฃผ์–ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. 

 

 

VintageAppMaker/GithubSearcher

github api . Contribute to VintageAppMaker/GithubSearcher development by creating an account on GitHub.

github.com

๐Ÿคœ Elvis ์—ฐ์‚ฐ์ž ( ?: ์ƒ๊ธด๋ชจ์–‘์ด ์—˜๋น„์Šคํ”„๋ ˆ์Šฌ๋ฆฌ ํ—ค์–ด์Šคํƒ€์ผ๊ณผ ๊ฐ™๋‹ค๊ณ  ๋ช…๋ช…๋จ)๋Š” ๋„์ฒดํฌ๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” ์—ฐ์‚ฐ์ž์ด๋‹ค. 

package others

fun main(args: Array<String>) {

    val lst = listOf<Note>(
            StudyNote("์ธ๋ฌธํ•™", "๋ฐฐ์›Œ์•ผํ•จ"),
            WorkNote(1, "2019.07.08", "๋ฒ„๊ทธ๋ถ„์„", "snake"),
            Doodle("๊ทธ๋ƒฅ๋‚™์„œ์ž„", "๋งˆ๊ตฌ ๊ทธ๋ฆผ๊ทธ๋ฆฌ๋‹ค".toByteArray() )
    )

    // sealed class๋Š” ํ†ต์‹ ํ”„๋กœํ† ์ฝœ ๋˜๋Š” RecyclerView์˜ ๋‹ค์–‘ํ•œ ๋ฐ์ดํ„ฐ์— ์‚ฌ์šฉ๋จ
    lst.forEachIndexed { index, note ->

        println("[$index]------------------------")
        when(note){
            is StudyNote -> {println ("๊ณต๋ถ€๋…ธํŠธ: ${note.title}\n${note.content}")}
            is WorkNote  -> {println ("์—…๋ฌด๋…ธํŠธ: ${note.number}:${note.title}\n${note.author}")}
            is Doodle    -> {println ("๋‚™์„œ๋…ธํŠธ: ${note.memo}\n${note.Drawing.toList()} ")}
            else         -> {}
        }
        println("---------------------------\n")

    }

    // ?: ์—ฐ์‚ฐ์ž๋Š” ๋„์ฑ„ํฌ๋ฅผ ๊ฐ„๋‹จํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•  ๋•Œ ์‚ฌ์šฉํ•จ
    var nCheck : String? = null
    println(nCheck ?: "null")
    println(nCheck ?: return)

    println("์ถœ๋ ฅ์•ˆ๋จ")

}

sealed class Note
data class StudyNote(var title : String, var content : String) : Note()
data class WorkNote(val number : Int, val date : String, var title : String, val author :String) : Note()
data class Doodle  (var memo : String, var Drawing : ByteArray) : Note()

 

์‹คํ–‰๊ฒฐ๊ณผ

[0]------------------------
๊ณต๋ถ€๋…ธํŠธ: ์ธ๋ฌธํ•™
๋ฐฐ์›Œ์•ผํ•จ
---------------------------

[1]------------------------
์—…๋ฌด๋…ธํŠธ: 1:๋ฒ„๊ทธ๋ถ„์„
snake
---------------------------

[2]------------------------
๋‚™์„œ๋…ธํŠธ: ๊ทธ๋ƒฅ๋‚™์„œ์ž„
[-21, -89, -120, -22, -75, -84, 32, -22, -73, -72, -21, -90, -68, -22, -73, -72, -21, -90, -84, -21, -117, -92] 
---------------------------

null

 

Comments