Kotlin 문법 정리.



// 주석.
/* 주석 */
// private 현재 파일에서만.
// internal 같은 모듈에서만. 
// protected 상속받은 클래스에서.
class Test {

    // Double, float, Long, int, Short, Byte, String, Char
    val hello : String = """ hi
                            hello """


    // val 읽기 전용, var 쓰기 가능.
    val a: Int = 1  
    var b: Int? = null  
    // lateinit 늦은 초기화.
    lateinit private var mHandler: Handler

    fun voidFunc() {}
    fun sum(a: Int, b: Int) = a + b
    fun sum(a: Int, b: Int = 10): Int { return a + b }

    // int? 널타입 리턴 가능.
    fun parseInt(str: String): Int? { return null }
    
    fun NullCheck() {
        var aa: Int? = 11
        var bb: Int? = null  
        var cc: Int = aa!! // !! 널이 아님을 보증.

        var str: String? = null
        var ch : Char = str?.get(1) // ?. 널이 아닐때 호출
        var ch2 : Char = str?.get(1) ?: 'a' // ?: 널일때 호출
    }


    fun StringTemplates() { 
        val s1 = "a is $a" 
        val s2 = "${s1.replace("is", "was")}, but now is $a"
        val str = "hi"
        println("$str Hello") // hi hello
        println("${str}Hello") // hihello
    }

    fun maxOf(a: Int, b: Int) = if (a > b) a else b
    fun maxOf(a: Int, b: Int): Int {
        if (a > b) {
            return a
        } else {
            return b
        }
    }

    fun printProduct(arg1: String, arg2: String) {
        val x = parseInt(arg1)
        val y = parseInt(arg2)
    
        // Using `x * y` yields error because they may hold nulls.
        if (x != null && y != null) {
            // x and y are automatically cast to non-nullable after null check
            println(x * y)
        }
        else {
            println("'$arg1' or '$arg2' is not a number")
        }    
    }


    fun Typechecks(obj: Any): Int? {
        if (obj is String) {
            // `obj` 는 자동으로 `String`으로 형변환 된다.
            // 현변환은 이 블록 안에서만 유효.
            return obj.length
        }
        // `obj`는 `Any` 타입 이다.

        val b: String? = null
        println(b?.length)

        val listWithNulls: List<String?> = listOf("Kotlin", null)
        for (item in listWithNulls) {
            item?.let { println(it) } // prints Kotlin and ignores null
        }

        // val l = b?.length ?: -1
        val l: Int = if (b != null) b.length else -1
        val l2 = b!!.length


        val aInt: Int? = a as? Int

        val nullableList: List<Int?> = listOf(1, 2, null, 4)
        val intList: List<Int> = nullableList.filterNotNull()

        return null
    }

    fun Loop() { 
        val items = listOf("apple", "banana", "kiwifruit")
        for (item in items) { println(item) }
        for (item: Int in ints) { println(item) }

        for (i in 1..3) { println(i) }
        for (i in 6 downTo 0 step 2) { println(i) }

        for (i in array.indices) {  println(array[i]) }
        for ((index, value) in array.withIndex()) {
            println("the element at $index is $value")
        }

        var x = 9
        while (x > 0) { x-- }
        
        do {
            //val y = retrieveData()
        } while (y != null)
    }

    fun WhenExpression(obj: Any): String =
    when (obj) {
        1          -> "One"
        "Hello"    -> "Greeting"
        is Long    -> "Long"
        !is String -> "Not a string"
        else       -> "Unknown"
    }

    fun Collections() { 

        val num:Array<int> = arrayOf(1, 2, 3)


        for (item in items) { println(item) }
        when {
            "orange" in items -> println("juicy")
            "apple" in items -> println("apple is fine too")
        }

        val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
        fruits
        .filter { it.startsWith("a") }
        .sortedBy { it }
        .map { it.toUpperCase() }
        .forEach { println(it) }

    }


}


class Test2{}
val t = Test2()

class Test3(var value: String) 

class Test4(var name: String) : Test3(value)
{
    constructor(name: String):this(name) {} // 생성자.
    init {  } // 
}

// abstract 추상클래스.
// interface

// 확장함수.
fun Int.Test() = this * 2
val aaa: Int = 3
aaa.Test()

// 형변환.
val aaa: Int = 3
val bbb = aaa.toString()
val ccc = Int.parseInt("33")

// let with apply run also 확장함수, 리턴형 차이.
var ttt = str?.let{ Int.parseInt(it) } // str을 {}안에서 it로 지칭. 결과리턴.
var ttt = str?.also{ Int.parseInt(it) } // str을 {}안에서 it로 지칭. str리턴.
var ttt = str?.apply{ this = "test" } // str의 상태를 변화시키고 str을 리턴.
var ttt = str?.run{ Int.parseInt(this) } // str을 {}안에서 it로 지칭. 결과리턴.
with(str) { Int.parseInt(this) } // str을 this로 지칭. str이 널이 아닐때만. 결과리턴.

댓글

이 블로그의 인기 게시물

파이썬 vscode에서 자동 코드 정렬. Formatter.

Unity3D git 저장소에 올릴때 필요없는 파일 제외하기. gitignore

플러터(flutter) 개발 참고 사이트들.