[πŸ“±|App] ν—·κ°ˆλ¦¬λŠ” Kotlin 문법 정리

minseok128Β·2024λ…„ 10μ›” 20일
1

Jetpack Composeλ₯Ό ν™œμš©ν•œ μ•ˆλ“œλ‘œμ΄λ“œ μ• ν”Œλ¦¬μΌ€μ΄μ…˜ κ°œλ°œμ„ μ‹œμž‘ν•  λ•Œ, μ½”ν‹€λ¦°μ˜ μ„Έλ ¨λœ 문법을 λ¨Όμ € μ •λ¦¬ν•˜κ³  λ“€μ–΄κ°€λ©΄ 도움이 λ©λ‹ˆλ‹€. 특히 λ‹€λ₯Έ 언어와 μ°¨λ³„ν™”λ˜λŠ” ν—·κ°ˆλ¦΄ 수 μžˆλŠ” 뢀뢄듀을 μœ„μ£Όλ‘œ 정리해 λ³΄μ•˜μŠ΅λ‹ˆλ‹€.

μ›ΉμœΌλ‘œ 접속 κ°€λŠ₯ν•œ μ½”ν‹€λ¦° playgroundμ—μ„œ 직접 컴파일 ν•΄λ³΄λ©΄μ„œ κ³΅λΆ€ν•΄λ³΄μ„Έμš”!
https://play.kotlinlang.org

λ³€μˆ˜ μ„ μ–Έ

  • 일반 κ·œμΉ™

    • λͺ¨λ“  λ³€μˆ˜λŠ” 객체λ₯Ό κ°€λ¦¬ν‚€λŠ” 레퍼런슀!
    • var, val μ‚¬μš©
      • val둜 μ„ μ–Έν–ˆλ‹€κ³  객체의 맴버 값도 λ³€κ²½ν•  수 μ—†λŠ” 것은 μ•„λ‹˜ β†’ c++의 const와 닀름
    • νƒ€μž… λͺ…μ‹œμ™€ μΆ”λ‘ 
      • var data: Int = 10 ← μ΄λ ‡κ²Œ νƒ€μž…μ„ λͺ…μ‹œ κ°€λŠ₯
      • λŒ€μž…μ„ 톡해 μΆ”λ‘  κ°€λŠ₯ν•˜λ‹€λ©΄ μƒλž΅ κ°€λŠ₯
        • var a; a = 10; ← λΆˆκ°€λŠ₯
        • var a: Int; a = 10; ← κ°€λŠ₯
  • μ΄ˆκΈ°κ°’ ν• λ‹Ή

    • 2κ°€μ§€ 경우
      • ν•¨μˆ˜ λ‚΄λΆ€ β†’ μ΄ˆκΈ°κ°’ ν• λ‹Ή ν•„μˆ˜ μ•„λ‹˜
        • κ·ΈλŸ¬λ‚˜ μ΄ˆκΈ°ν™” λ˜μ§€ μ•Šμ€ λ³€μˆ˜λ₯Ό 좜λ ₯ λ“±μœΌλ‘œ μ‚¬μš©ν•˜λ €κ³  ν•˜λ©΄ error
      • μ΅œμƒμœ„ μ„ μ–Έ, 클래슀 μ†μ„±μœΌλ‘œ μ„ μ–Έ β†’ μ΄ˆκΈ°κ°’ ν• λ‹Ή ν•„μˆ˜
    • μ΄ˆκΈ°ν™” 미루기
      • lateinit ν‚€μ›Œλ“œ
        • 2κ°€μ§€ 쑰건에 μΆ©μ‘±λœλ‹€λ©΄, lateinit var a: String ← κ°€λŠ₯
          1. var ν‚€μ›Œλ“œλ‘œ 선언될 것
          2. primitive type이 아닐 것
      • lazy ν‚€μ›Œλ“œ
        • val name: String by lazy { } ← μ΄λ ‡κ²Œ μ‚¬μš©λ˜λŠ” μ‹œμ μ— μ΄ˆκΈ°ν™” κ°€λŠ₯
        • { } 내뢀에 λͺ…μ‹œλœ 것듀이 ν•˜λ‚˜μ”© μ‹€ν–‰λ˜κ³  λ§ˆμ§€λ§‰ κ°’μœΌλ‘œ μ΄ˆκΈ°ν™”
          • val a: Int by lazy { 10; 20; 30 } ← 30으둜 μ΄ˆκΈ°ν™”

데이터 νƒ€μž…

  • primitive type ← Class둜 제곡됨

    • Byte(1byte), Short(2byte), Int(4byte), Long(8byte), Double, Float, Boolean
      • μ΄λ•Œ 숫자λ₯Ό λ‚˜νƒ€λ‚΄λŠ” νƒ€μž…μ€ 좔상 클래슀 Number 상속
    • var a: Int = 10, var b: Double? = null ← κ°€λŠ₯
  • λ¬Έμžμ™€ λ¬Έμžμ—΄

    • Char νƒ€μž…μ€ Numberλ₯Ό μƒμ†ν•˜μ§€ μ•ŠμŒ β†’ 계산 등에 μ‚¬μš©λ  수 μ—†μŒ
    • String νƒ€μž…μ€ λ”°μ˜΄ν‘œ, μ‚Όμ€‘λ”°μ˜΄ν‘œλ‘œ ν‘œν˜„
      • λ¬Έμžμ—΄ νƒ¬ν”Œλ¦Ώ: "plus: ${a + 10 + pi()}", "plus: $a" ← μ΄λ ‡κ²Œ κ°€λŠ₯
  • Any, Unit, Nothing

    • Any: μ΅œμƒμœ„ 클래슀둜 λͺ¨λ“  클래슀 가리킬 수 있음
      • λ‚΄κ°€ μƒˆλ‘œ μ •μ˜ν•œ class도 λ°˜λ“œμ‹œ μžλ™μœΌλ‘œ Anyλ₯Ό μƒμ†ν•˜κ²Œ 됨
    • Unit: return이 μ—†λ‹€λŠ” 것을 λͺ…μ‹œμ μœΌλ‘œ λ‚˜νƒ€λ‚΄κΈ° μœ„ν•œ 클래슀
      • Unit으둜 μ„ μ–Έλœ λ³€μˆ˜μ—λŠ” Unit λΉΌκ³  μ–΄λŠ 것도 λ‹΄κΈΈ 수 μ—†μŒ
        • Unit μΈμŠ€ν„΄μŠ€λŠ” 싱글톀, final ν‚€μ›Œλ“œλ‘œ 상속도 λ§‰ν˜€μžˆμŒ
    • Nothing: nullλ§Œμ„ λ‹΄κΈ° μœ„ν•œ 클래슀, return이 항상 null일 λ•Œ μ‚¬μš©
      • var a: Nothing? = null ← null을 μ œμ™Έν•œ κ·Έ 무엇도 λ‹΄μ§€ λͺ»ν•¨
      • λ§Œμ•½ ν•¨μˆ˜μ˜ return νƒ€μž…μ΄ κ·Έμ € Noting이라면 λ°˜λ“œμ‹œ Exception을 λ˜μ Έμ•Όν•¨

ν•¨μˆ˜ μ„ μ–Έ

  • fun add(a: Int, b: Int): Int

    • νŒŒλΌλ―Έν„°λŠ” var, val νƒ€μž…μ„ μ‚¬μš©ν•  수 μ—†μŒ β†’ μžλ™μœΌλ‘œ λ°˜λ“œμ‹œ val
      • λ”°λΌμ„œ 기타 언어와 달리 νŒŒλΌλ―Έν„° λ³€μˆ˜μ˜ 값을 μˆ˜μ •ν•  수 μ—†μŒ
    • return νƒ€μž… λͺ…μ‹œν•˜μ§€ μ•Šμ„ μ‹œ, Unit으둜 κ°„μ£Ό
  • fun add(a: Int, b: Int, isDeciaml: Boolean = true): Int

    • νŒŒλΌλ―Έν„°μ˜ κΈ°λ³Έ 값을 μ§€μ •ν•  수 있음 β†’ 이 경우 ν•¨μˆ˜ν˜ΈμΆœ μ‹œ ν•΄λ‹Ή νŒŒλΌλ―Έν„°λŠ” μ‚¬μš©ν•˜μ§€ μ•Šμ•„λ„ 됨
    • κΈ°λ³Έ 값이 μ§€μ •λœ νŒŒλΌλ―Έν„°κ°€ λ°˜λ“œμ‹œ κ°€μž₯ 뒀에 λͺ¨μ—¬μžˆμ„ ν•„μš”λŠ” μ—†μŒ
      • 단, 이 경우 ν•¨μˆ˜ 호좜 μ‹œ 가독성이 λ–¨μ–΄μ§ˆ 수 있음 β†’ val result1 = add(5, b = 10)
        • named parameter

Collection Type

  • Array

    • κΈ°λ³Έ
      • val data1: Array<Int> = Array(3, {0}) ← 기본적으둜 μ œλ„€λ¦­μœΌλ‘œ λ‚˜νƒ€λƒ„
        • μ΄λ•Œ {0} λŠ” λžŒλ‹€μ‹μœΌλ‘œ val data: Array<Int> = Array(3) { 1 } ← 이 경우 λͺ¨λ‘ 1둜 μ΄ˆκΈ°ν™” 됨
      • [idx], get(idx), set(idx, value) ← μ΄λŸ°μ‹μœΌλ‘œ μ ‘κ·Ό κ°€λŠ₯
      • val data = arrayOf<Int>(10, 20, 30) ← 이런 μ‹μœΌλ‘œ μ œλ„€λ¦­ ν•¨μˆ˜λ₯Ό 톡해 μ΄ˆκΈ°ν™”λ„ κ°€λŠ₯
    • primitive type에 λŒ€ν•΄μ„œ
      • 기초 νƒ€μž…μ€ 자주 μ‚¬μš©ν•˜λ―€λ‘œ 클래슀둜 ν‘œν˜„λ˜μ–΄μžˆμŒ
        • BooleanArray, ByteArray, CharArray, IntArray, etc…
        • val data: IntArray = IntArray(3, {0}), val data = intArrayOf(1, 2, 3)
  • List, MutableList

    • μˆœμ„œκ°€ μžˆλŠ” 데이터 μ§‘ν•©, 데이터 쀑볡 ν—ˆμš©
      • λΆˆλ³€κ³Ό κ°€λ³€μœΌλ‘œ λΆ„λ₯˜λ¨ β†’ λΆˆλ³€ λ¦¬μŠ€νŠΈλŠ” μ΄ˆκΈ°ν™” 이후 κ°’ μˆ˜μ •, μΆ”κ°€, μ‚­μ œ λΆˆκ°€λŠ₯
    • val data: List<Int> = List<Int>(3, {0}), val data = listOf<Int>(1, 2, 3)
      • mList.add(1), mList.add(3, 1), mutableList.set(2, 9), mutableList[2] = 1
  • Set, MutableSet

    • μˆœμ„œκ°€ μ—†μœΌλ©°, 데이터 쀑볡을 λΆˆν—ˆμš©
      • λΆˆλ³€κ³Ό κ°€λ³€μœΌλ‘œ λΆ„λ₯˜λ¨
  • Map, MutableMap

    • 킀와 κ°’μœΌλ‘œ 이루어진 데이터 μ§‘ν•©, μˆœμ„œκ°€ μ—†κ³ , ν‚€μ˜ 쀑볡은 λΆˆν—ˆμš©
      • λΆˆλ³€κ³Ό κ°€λ³€μœΌλ‘œ λΆ„λ₯˜λ¨
    • μ‚¬μš© μ˜ˆμ‹œ
      • var map = mapOf<String, String>(Pair("one", "1"), "two" to "2")
        • map.get("one")

쑰건문

  • if ~ else

    • 기쑴의 μ–Έμ–΄λ“€κ³Ό μ‚¬μš©λ²•μ€ 동일
    • 계산식(ν‘œν˜„μ‹)μœΌλ‘œλ„ μ‚¬μš© κ°€λŠ₯ β†’ μ‚Όν•­ μ—°μ‚°μž μ—†μŒ
      • var res = if (data > 0) { print("p"); true; } else { print("f"); false; }
  • when

    • switch 역할을 μˆ˜ν–‰ν•˜λŠ” 것, if ~ else 처럼 ν‘œν˜„μ‹μœΌλ‘œλ„ μ‚¬μš© κ°€λŠ₯(이 경우 else λ°˜λ“œμ‹œ λͺ…μ‹œ)
    • μ‚¬μš© μ˜ˆμ‹œ
      • ( ) 내에 dataλ₯Ό λͺ…μ‹œν•˜λ©΄ λ‹€μŒκ³Ό 같은 것듀이 κ°€λŠ₯
        when (data) {
            "hello" -> println("data is hello")
            "world" -> println("data is world")
            else -> println("data is not valid data")
        }
        
        when (data) {
            is String -> println("data is String")
            20, 30 -> println("data is 20 or 30")
            in 1..10 -> println("data is 1..10")
            else -> println("data is not valid data")
        }
      • ( )λ₯Ό μƒλž΅ν•˜λŠ” 경우 쑰건문을 μž‘μ„±ν•  수 있음
        when {
            data <= 0 -> println("data is <= 0")
            data > 100 -> println("data is > 100")
            else -> println("data is not valid")
        }
        
        val result = when {
            data <= 0 -> "data is <= 0"
            data > 100 -> "data is > 100"
            else -> "data is not valid"
        }
        

반볡문

  • for

    • μ›λž˜μ²˜λŸΌλ„ μ“Έ 수 μžˆμ§€λ§Œ λ‹€μŒκ³Ό 같이 ν™œμš©ν•  μˆ˜λ„ 있음
      1. for (i in 1 .. 10) { … } ← 1 λΆ€ν„° 10κΉŒμ§€
      2. for (i in 1 until 10) { … } ← 1λΆ€ν„° 9κΉŒμ§€
      3. for (i in 2 .. 10 step 2) { … } ← 2λΆ€ν„° 10κΉŒμ§€ 2μ”© 증가
      4. for (i in 1 downTo 10) { … } ← 10λΆ€ν„° 1κΉŒμ§€ 1식 κ°μ†Œ
      5. for (i in arrayOf<Int>(0, 1, 2).indices) { … } ← μ»¬λ ‰μ…˜ νƒ€μž… 데이터 반볡
      6. for ((index, value) in arrayOf<Int>(0, 1, 2).withIndex()) { … }
  • while

    • λ‹€λ₯Έ 언어와 λ™μΌν•˜κ²Œ λ™μž‘

Class

  • 클래슀 μ„ μ–Έ

    • 클래슀의 λ§΄λ²„λŠ” μƒμ„±μž(μ£Ό, 보쑰), λ³€μˆ˜, ν•¨μˆ˜, 클래슀둜 ꡬ성됨
      • λͺ¨λ“  맴버 λ³€μˆ˜λŠ” μƒμ„±μžμ—μ„œ λ°˜λ“œμ‹œ μ΄ˆκΈ°ν™”ν•  것, ν˜Ήμ€ lateinit ν‚€μ›Œλ“œ μ‚¬μš©
    • 클래슀 내에 λ‹€λ₯Έ 클래슀 μ„ μ–Έ κ°€λŠ₯
    • μΈμŠ€ν„΄μŠ€λ₯Ό 생성할 λ•Œ new ν‚€μ›Œλ“œ μ‚¬μš©ν•˜μ§€ μ•ŠμŒ
      • val user = User("minseok128")
    • μƒμ„±μž(μ£Ό μƒμ„±μž, 보쑰 μƒμ„±μž)
      • μ£Ό μƒμ„±μžλ§Œ μ„ μ–Έ, 보쑰 μƒμ„±μžλ§Œ μ„ μ–Έ, λ‘˜ λ‹€ μ„ μ–Έ λͺ¨λ‘ κ°€λŠ₯
  • μ£Ό μƒμ„±μž

    • μ£Ό μƒμ„±μž μ„ μ–Έμ˜ μ—¬λŸ¬ ν˜•νƒœ
      1. μš°μ„  클래슀λͺ… 뒀에 λ‹€μŒκ³Ό 같은 λ°©λ²•μœΌλ‘œ
        1. class User constructor() { } ← class λͺ…μΉ­ 뒀에 constructor() λͺ…μ‹œ ν˜•νƒœ
        2. class User() { } ← constructor μƒλž΅ ν˜•νƒœ
      2. init { } 을 μ‚¬μš©ν•˜μ—¬ μ£Ό μƒμ„±μžμ˜ λ³Έλ¬Έ μž‘μ„± κ°€λŠ₯
        • 선택적 κ΅¬ν˜„
      3. μ£Ό μƒμ„±μž λ§€κ°œλ³€μˆ˜λ₯Ό μ¦‰μ‹œ 클래슀 맴버 λ³€μˆ˜λ‘œ λ³€ν™˜
        1. class User(val name: String, private var count: Int) ← μ¦‰μ‹œ λ§΄λ²„λ‘œ μ„ μ–Έ
        2. class User(name: String, count: Int) ← λ§€κ°œλ³€μˆ˜ 였직 init λ‚΄μ—μ„œλ§Œ μ ‘κ·Ό κ°€λŠ₯
    • μ½”ν‹€λ¦° ν΄λž˜μŠ€λŠ” μ£Όμƒμ„±μž κΈ°μ€€μœΌλ‘œ λ™μž‘!
  • 보쑰 μƒμ„±μž

    • 클래슀 본문에 constructor ν‚€μ›Œλ“œλ‘œ μ„ μ–Έν•˜λŠ” ν•¨μˆ˜ β†’ λ‹€λ₯Έ λ§€κ°œλ³€μˆ˜λ‘œ μ—¬λŸ¬ 개 μ„ μ–Έ κ°€λŠ₯
      • μ˜ˆμ‹œ
        class User {
            constructor(name: String) {
                println("first constructor")
            }
            
            constructor(name: String, count: Int) {
                println("second constructor")
            }
        }
      • λ§Œμ•½ val ν‚€μ›Œλ“œλ‘œ μ„ μ–Έλœ 맴버 λ³€μˆ˜λ₯Ό 생성 μ‹œμ μ— νŠΉμ • κ°’μœΌλ‘œ μ΄ˆκΈ°ν™”ν•˜κ³  μ‹Άλ‹€λ©΄
        β†’ λ°˜λ“œμ‹œ μ£Ό μƒμ„±μžλ₯Ό ν˜ΈμΆœν•˜λŠ” μ‹μœΌλ‘œ 진행해야함
    • λ§Œμ•½ μ£Ό μƒμ„±μžκ°€ μ‘΄μž¬ν•œλ‹€λ©΄? β†’ λͺ¨λ“  보쑰 μƒμ„±μžλŠ” μ–΄λ–€ μ‹μœΌλ‘œλ“  this() 톡해 μ£Όμƒμ„±μžλ₯Ό 호좜
      • μ˜ˆμ‹œ
        class User(name: String) {
            init {
                println("main constructor")
            }
        
            constructor(name: String, count: Int): this(name) {
                println("first constructor")
            }
        
            constructor(name: String, count: Int, email: String): this(name, count) {
                println("second constructor")
            }
        }
      • μ£Όμƒμ„±μžκ°€ μ—†λ‹€λ©΄ ν˜ΈμΆœν–ˆλ‹€κ³  μΉ¨
  • 상속과 μƒμ„±μž

    • λΆ€λͺ¨
      • open class Animal(val name: String) { } ← λ°˜λ“œμ‹œ open ν‚€μ›Œλ“œ λͺ…μ‹œ
    • μžμ‹
      • μ£Όμƒμ„±μž ν˜ΈμΆœν•˜ λ“― λ°˜λ“œμ‹œ λΆ€λͺ¨μ˜ μƒμ„±μžλ₯Ό ν˜ΈμΆœν•  것
        open class Animal(val name: String) {}
        
        class Sub1(name: String): Animal(name) {}
        
        class Sub2 {
        	constructor(name: String): super(name) { }
        }
        • μ£Ό μƒμ„±μžκ°€ μžˆλ‹€λ©΄ 상속 μ‹œμ μ—μ„œ λΆ€λͺ¨μ˜ λ§€κ°œλ³€μˆ˜λ₯Ό 적절히 λ„˜κ²¨μ€˜μ•Όλ§Œ 함
        • μ£Ό μƒμ„±μžκ°€ μ—†λ‹€λ©΄ 보쑰 μƒμ„±μžμ—μ„œ superλ₯Ό 톡해 ν˜ΈμΆœν•  수 있음
  • μ˜€λ²„λΌμ΄λ”©

    • λΆ€λͺ¨
      • μ˜€λ²„λΌμ΄λ”©μ„ ν—ˆμš©ν•˜λŠ” λ³€μˆ˜μ™€ ν•¨μˆ˜ μ„ μ–Έλ¬Έ μ•žμ— λ°˜λ“œμ‹œ open ν‚€μ›Œλ“œ λͺ…μ‹œ
    • μžμ‹
      • μž¬μ •μ˜ν•˜κΈ° μœ„ν•΄ μ„ μ–Έλ¬Έ μ•žμ— override ν‚€μ›Œλ“œ λͺ…μ‹œ
    • λ³€μˆ˜λ₯Ό μ˜€λ²„λΌμ΄λ”© ν•˜λŠ” 이유 β†’ λͺ¨λ“  맴버 λ³€μˆ˜λŠ” μ΄ˆκΈ°ν™”λ˜μ–΄μ•Όν•¨ β†’ λΆ€λͺ¨ 값을 λ°”κΎΈλ €λ©΄ μž¬μ •μ˜ 뿐
      • var ν‚€μ›Œλ“œλ‘œ μ„ μ–Έλœ λ³€μˆ˜λ„ μž¬μ •μ˜ κ°€λŠ₯
  • μ ‘κ·Ό μ œν•œμž

    • μ ‘κ·Ό μ œν•œμžκ°€ μƒλž΅λœ 경우 β†’ public을 의미
    • 2κ°€μ§€ μƒν™©μ—μ„œ λ‹€λ₯Έ 의미둜 μ‚¬μš©
      • 파일의 μ΅œμƒμœ„μ—μ„œ μ‚¬μš©
        • public: λͺ¨λ“  νŒŒμΌμ—μ„œ κ°€λŠ₯
        • internal: 같은 λͺ¨λ“ˆ λ‚΄μ—μ„œ κ°€λŠ₯
        • protected: μ‚¬μš© λΆˆκ°€
        • private: 파일 λ‚΄λΆ€μ—μ„œλ§Œ μ‚¬μš© κ°€λŠ₯
      • 클래슀 맴버에 λŒ€ν•΄μ„œ μ‚¬μš©
        • public: λͺ¨λ“  ν΄λž˜μŠ€μ—μ„œ κ°€λŠ₯
        • internal: 같은 λͺ¨λ“ˆ λ‚΄μ—μ„œ κ°€λŠ₯
        • protected: 상속 κ΄€κ³„μ˜ ν•˜μœ„ ν΄λž˜μŠ€μ—μ„œ κ°€λŠ₯
        • private: 클래슀 λ‚΄λΆ€μ—μ„œ κ°€λŠ₯

λ‹€μ–‘ν•œ 클래슀

  • 데이터 클래슀

    • 데이터λ₯Ό ν‘œν˜„ν•˜λŠ”λ° λͺ©μ μžˆλŠ” 클래슀 VO(value-object)라고도 λΆˆλ¦¬μ›€
      • data class DataClass(val name: String, val email: String, val age: Int)
    • 차이점: 일반 class와 거의 μœ μ‚¬ν•˜μ§€λ§Œ λ‹€λ₯Έ 점이 있음
      • equals ν•¨μˆ˜
        • μ£Ό μƒμ„±μžμ˜ 맴버 λ³€μˆ˜λ“€μ˜ 값이 λ™μΌν•˜λ‹€λ©΄ true ← μ›λž˜λŠ” λ™μΌν•œ 객체인지λ₯Ό 확인
      • toString ν•¨μˆ˜
        • μ£Ό μƒμ„±μžμ˜ 맴버 λ³€μˆ˜λ“€μ„ λ‚˜μ—΄ν•œ String return ← μ›λž˜λŠ” λ¬΄μ˜λ―Έν•œ κ°’ 좜λ ₯
  • 였브젝트 클래슀

    • 읡λͺ… 클래슀λ₯Ό λ§Œλ“€ λͺ©μ  β†’ κ·Έ νƒ€μž…μ€ Any둜 μ·¨κΈ‰
    • 주둜 μƒμœ„ 클래슀λ₯Ό μƒμ†ν•˜μ—¬ 닀뀄짐
      open class Super {
          open var data = 10
          open fun some() {
              println("I am super some() : $data")
          }
      }
      
      val obj = object : Super() {
          override var data = 20
          override fun some() {
              println("I am object some() : $data")
          }
      }
  • μ»΄νŒ¨λ‹ˆμ–Έ 클래슀
    • static 맴버와 λ™μΌν•œ κΈ°λŠ₯을 제곡, 클래슀 λ‚΄λΆ€μ˜ 클래슀둜 μ„ μ–Έ
      class MyClass {
          companion object {
              var data = 10
              fun some() {
                  println(data)
              }
          }
      }
      
      fun main() {
          MyClass.data = 20  // OK
          MyClass.some()     // OK
      }

λ‹€μ–‘ν•œ ν•¨μˆ˜

  • λžŒλ‹€ ν•¨μˆ˜

    • 읡λͺ… ν•¨μˆ˜ μ •μ˜ 기법, 주둜 κ³ μ°¨ν•¨μˆ˜μ˜ λ§€κ°œλ³€μˆ˜ ν˜Ήμ€ λ°˜ν™˜κ°’μœΌλ‘œ ν™œμš©λ¨
    • ν™œμš© μ˜ˆμ‹œ
      • val sum = { a: Int, b: Int -> a + b } ← 이 경우 μ•„λž˜μ™€ 같이 νƒ€μž…μ΄ 좔둠됨
        • val sum: (Int, Int) -> Int = { a: Int, b: Int -> a + b }
      • println({ a: Int, b: Int -> a + b }(10, 20))
      • val sum = { a: Int, b: Int -> println("+"); a + b; } ← λ§ˆμ§€λ§‰ ν‘œν˜„μ‹μ΄ return
      • val func1 = { println("hi") } ← λ§€κ°œλ³€μˆ˜ μ—†λŠ” 경우 ν™”μ‚΄ν‘œ μƒλž΅ κ°€λŠ₯
      • val func1: (Int) -> Unit = { println(it) } ← λ§€κ°œλ³€μˆ˜ ν•˜λ‚˜ it으둜 ν‘œν˜„, ν™”μ‚΄ν‘œ μƒλž΅
  • νƒ€μž…

    • ν•¨μˆ˜μ˜ νƒ€μž… μ„ μ–Έ
      • val some: () -> Int = { 42 }
    • νƒ€μž… 별칭
      • typealias MyFunType = (Int, Int) -> Unit
      • 별칭을 λ”°λ‘œ μ§€μ • κ°€λŠ₯
    • ν•¨μˆ˜ λ§€κ°œλ³€μˆ˜ νƒ€μž… μƒλž΅
      • μ–΄λ–€ μ‹μœΌλ‘œλ“  μΆ”λ‘  κ°€λŠ₯ν•˜λ©΄ μƒλž΅ κ°€λŠ₯
        typealias MyFunType = (Int, Int) -> Boolean
        
        val someFun: MyFunType = { no1, no2 -> no1 > no2 }
        
        val someFun2: (Int, Int) -> Boolean = { no1, no2 -> no1 > no2 }
        
        val someFun3: (no1: Int, no2: Int) -> Boolean = { no1, no2 -> no1 > no2 }
  • κ³ μ°¨ ν•¨μˆ˜

    • ν›„ν–‰ λžŒλ‹€ 전달: ν•¨μˆ˜μ˜ λ§ˆμ§€λ§‰ λ§€κ°œλ³€μˆ˜κ°€ ν•¨μˆ˜μΌ λ•Œ 인수둜 전달될 λžŒλ‹€ν•¨μˆ˜λŠ” κ΄„ν˜Έ λ°–μœΌλ‘œ 배치 κ°€λŠ₯
      fun hotFun2(data: Int, arg: (Int) -> Boolean): Int {
          return if (arg(data)) 100 else 0
      }
      
      val result3 = hotFun2(10) {
          println("high order function")
          it > 50
      }
      
      println(result3)
  • null μ•ˆμ „μ„± μ—°μ‚°μž
    • ?. μ—°μ‚°μž ← 널 ν—ˆμš©μœΌλ‘œ μ„ μ–Έλœ λ³€μˆ˜μ˜ 맴버에 μ ‘κ·Όν•˜κΈ° μœ„ν•΄ μ‚¬μš©, null을 returnν•  수 있음
    • ? μ—°μ‚°μž ← λ³€μˆ˜κ°€ null을 κ°€μ§ˆ 수 μžˆμ„ λ•Œ type μ˜†μ— λͺ…μ‹œ
    • !! μ—°μ‚°μž ← 객체가 null일 λ•Œ μ˜ˆμ™Έλ₯Ό λ°œμƒμ‹œν‚΄, null은 ν—ˆμš©ν•˜μ§€λ§Œ 였λ₯˜λŠ” λ°œμƒ

κ΅¬ν˜„λ˜μ–΄ μžˆλŠ” ν•¨μˆ˜ν˜• ν”„λ‘œκ·Έλž˜λ° ν•¨μˆ˜

  • forEach: μˆœνšŒν•˜λ©΄μ„œ 각 μš”μ†Œμ— λŒ€ν•΄ action을 μˆ˜ν–‰

    • public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit
    • μ˜ˆμ‹œ: listOf(1, 2, 3).forEach { println(it) }
  • filter: 각 μš”μ†Œμ— λŒ€ν•œ predicate ν•¨μˆ˜μ˜ return이 참인 μš”μ†Œλ“€λ§Œ ν¬ν•¨λœ 리슀트λ₯Ό 생성

    • public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T>
    • μ˜ˆμ‹œ: val even = listOf(1, 2, 3, 4).filter { it % 2 == 0 }
  • partition: 각 μš”μ†Œμ— λŒ€ν•˜ predicate ν•¨μˆ˜ 결과둜 λΆ„λ¦¬λœ 2개의 리슀트λ₯Ό νŽ˜μ–΄λ‘œ 생성

    • public fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>>
    • μ˜ˆμ‹œ: val (even, odd) = listOf(1, 2, 3, 4).partition { it % 2 == 0 }
  • map: 각 μš”μ†Œμ— λŒ€ν•΄ transform ν•¨μˆ˜κ°€ 적용된 결과둜 이루어진 리슀트λ₯Ό 생성

    • public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R>
    • μ˜ˆμ‹œ: val doubled = listOf(1, 2, 3).map { it * 2 }
  • any: μš”μ†Œλ“€ 쀑 predicate ν•¨μˆ˜κ°€ 참인 μš”μ†Œκ°€ μ‘΄μž¬ν•˜λ©΄ trueλ₯Ό return

    • public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean
    • μ˜ˆμ‹œ: val hasEven = listOf(1, 2, 3).any { it % 2 == 0 }
  • reduce: 각 μš”μ†Œλ“€μ— operation을 μ μš©ν•˜μ—¬, ν•˜λ‚˜μ˜ κ°’μœΌλ‘œ λ§Œλ“€κ³  return

    • public inline fun <S, T: S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S
    • μ˜ˆμ‹œ: val sum = listOf(1, 2, 3, 4).reduce { acc, num -> acc + num }
  • distinct: μ€‘λ³΅λ˜λŠ” μš”μ†Œκ°€ 제거된 리슀트 λ°˜ν™˜

    • public fun <T> Iterable<T>.distinct(): List<T>
    • μ˜ˆμ‹œ: val unique = listOf(1, 2, 2, 3).distinct()
  • find/findLast: 쑰건을 λ§Œμ‘±ν•˜λŠ” κ°€μž₯ μ•ž/λ’€μ˜ μ›μ†Œλ₯Ό return, μ—†μœΌλ©΄ null

    • public inline fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T?
    • μ˜ˆμ‹œ: val firstEven = listOf(1, 2, 3).find { it % 2 == 0 }
  • groupBy: μ£Όμ–΄μ§„ key에 맞게 킀와 리슀트둜 이루어진 Map을 생성

    • public inline fun <T, K> Iterable<T>.groupBy(keySelector: (T) -> K): Map<K, List<T>>
    • μ˜ˆμ‹œ: val group = listOf("a", "bb", "ccc").groupBy { it.length }
  • maxByOrNull/minByOrNull: selector 값이 κ°€μž₯ 큰/μž‘μ€ μ›μ†Œλ₯Ό return, μ—†μœΌλ©΄ null

    • public inline fun <T, R: Comparable<R>> Iterable<T>.maxByOrNull(selector: (T) -> R): T? public inline fun <T, R: Comparable<R>> Iterable<T>.minByOrNull(selector: (T) -> R): T?
    • μ˜ˆμ‹œ: val maxString = listOf("a", "bb", "ccc").maxByOrNull { it.length } val minString = listOf("a", "bb", "ccc").minByOrNull { it.length }
profile
μ„Έκ³„λŠ” λ‚˜μ˜ ν‘œμƒ

4개의 λŒ“κΈ€

comment-user-thumbnail
2024λ…„ 10μ›” 21일

마침 내일 μ‹œν—˜μΈλ° λ„ˆλ¬΄ λ„μ›€λμ–΄μš”!

λ‹΅κΈ€ 달기
comment-user-thumbnail
2024λ…„ 10μ›” 25일

μš°μ™€ μœ μš©ν•˜κ³  ν—·κ°ˆλ¦΄λ§Œν•œ 문법 μ •λ¦¬λ„€μš”! κ°μ‚¬ν•©λ‹ˆλ‹€
저말고도 λ§Žμ€ λΆ„λ“€μ—κ²Œ 도움이 λ κ±°κ°™μ•„μš”!!γ…Žγ…Žγ…Ž

λ‹΅κΈ€ 달기
comment-user-thumbnail
2024λ…„ 10μ›” 26일

저도 이거 ν—·κ°ˆλ ·λŠ”λ° 이제 μš”μˆ κ³΅μ£Ό λ§ˆλ²• 덕뢄에 μ•ˆν—·κ°ˆλ¦΄λ“― ν•©λ‹ˆλ‹€ 뾰둜둱

λ‹΅κΈ€ 달기
comment-user-thumbnail
2024λ…„ 10μ›” 26일

였 이해가 쏙쏙 λ©λ‹ˆλ‹€

λ‹΅κΈ€ 달기