본문 바로가기
App/Android Kotlin

Kotlin(2) - 기본구문

by SeleniumBindingProtein 2022. 2. 4.
728x90
반응형

1. 패키지 정의

  • 패키지 사양은 소스 파일의 맨 위에 있어야 하며, 디렉토리와 패키지를 일치시킬 필요는 없음
fun main() {
    println("Hello world!")
}
  • 소스 파일은 파일 시스템에 임의로 배치할 수 있음
fun main(args: Array<String>) {
    println(args.contentToString())
}

2. 프로그램 진입점

  • Kotlin 애플리케이션의 진입점은 main 함수
fun main() {
    print("Hello ")
    print("world!")
}
  • 다른 형태의 인수 main은 다양한 수의 String 인수를 허용함
fun main(args: Array<String>) {
    println(args.contentToString())
}

3. 표준 출력으로 인쇄

  • print 인수를 표준 출력에 인쇄
print("Hello ")
print("world!")
  • println 인수를 인쇄하고, 줄 바꿈을 추가하여 다음에 인쇄하는 항목이 다음 줄에 표시되도록 함
fun main() {
    println("Hello world!")
    println(42)
}

4. 기능

  • Int 두 개의 매개변수와 Int 반환 유형이 있는 함수
fun sum(a: Int, b: Int): Int {
    return a + b
}

fun main() {
    print("sum of 3 and 5 is ")
    println(sum(3, 5))
}
  • 함수 본문은 표현식이 될 수 있으며, 반환 유형이 유추됨
fun sum(a: Int, b: Int) = a + b

fun main() {
    println("sum of 19 and 23 is ${sum(19, 23)}")
}
  • 의미 있는 값을 반환하지 않는 함수
fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}

fun main() {
    printSum(-1, 8)
}
  • Unit 반환 유형은 생략 가능
fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}

fun main() {
    printSum(-1, 8)
}

5. 변수

  • 읽기 전용 지역 변수는 키워드를 사용하여 정의되며, val. 한번만 값을 할당할 수 있음
fun main() {
    val a: Int = 1  // immediate assignment
    val b = 2   // `Int` type is inferred
    val c: Int  // Type required when no initializer is provided
    c = 3       // deferred assignment
    println("a = $a, b = $b, c = $c")
}
  • 재할당 가능한 변수 var 키워드를 사용함
fun main() {
    var x = 5 // `Int` type is inferred
    x += 1
    println("x = $x")
}
  • 최상위 수준에서 변수를 선언할 수 있음
val PI = 3.14
var x = 0

fun incrementX() { 
    x += 1 
}

fun main() {
    println("x = $x; PI = $PI")
    incrementX()
    println("incrementX()")
    println("x = $x; PI = $PI")
}

6. 클래스 및 인스턴스 생성

  • 클래스를 정의하려면 class 키워드를 사용해야 함
class Shape
  • 클래스의 속성은 선언 또는 본문에 나열될 수 있음
class Rectangle(var height: Double, var length: Double) {
    var perimeter = (height + length) * 2
}
  • 클래스 선언에 나열된 매개변수가 있는 기본 생성자는 자동으로 사용할 수 있음
class Rectangle(var height: Double, var length: Double) {
    var perimeter = (height + length) * 2 
}
fun main() {
    val rectangle = Rectangle(5.0, 2.0)
    println("The perimeter is ${rectangle.perimeter}")
}
  • 클래스 간의 상속은 콜론(:)으로 선언되며, 클래스는 기본적으로 final이고, 클래스를 상속가능하게 만들려면 open.으로 표시해야 됨
open class Shape

class Rectangle(var height: Double, var length: Double): Shape() {
    var perimeter = (height + length) * 2
}

7. 코멘트

  • 대부분의 최신 언어와 마찬가지로 Kotlin은 한 줄 및 여러 줄 주석으로 지원함
// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */
  • Kotlin의 블록 주석은 중첩될 수 있음
/* The comment starts here
/* contains a nested comment *⁠/
and ends here. */

8. 문자열 템플릿

fun main() {
    var a = 1
    // simple name in template:
    val s1 = "a is $a" 

    a = 2
    // arbitrary expression in template:
    val s2 = "${s1.replace("is", "was")}, but now is $a"
    println(s2)
}

9. 조건식

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

fun main() {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}
  • Kotlin에서도 if 표현식이 사용됨
fun maxOf(a: Int, b: Int) = if (a > b) a else b

fun main() {
    println("max of 0 and 42 is ${maxOf(0, 42)}")
}

10. for loop

fun main() {
    val items = listOf("apple", "banana", "kiwifruit")
    for (item in items) {
        println(item)
    }
}
  • or
fun main() {
    val items = listOf("apple", "banana", "kiwifruit")
    for (index in items.indices) {
        println("item at $index is ${items[index]}")
    }
}

11. while loop

fun main() {
    val items = listOf("apple", "banana", "kiwifruit")
    var index = 0
    while (index < items.size) {
        println("item at $index is ${items[index]}")
        index++
    }
}

12. when expression

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

fun main() {
    println(describe(1))
    println(describe("Hello"))
    println(describe(1000L))
    println(describe(2))
    println(describe("other"))
}

13. Ranges

  • in 연산자를 사용하여 숫자가 범위 내에 있는지 확인함
fun main() {
    val x = 10
    val y = 9
    if (x in 1..y+1) {
        println("fits in range")
    }
}
  • 숫자가 범위를 벗어났는지 확인함
fun main() {
    val list = listOf("a", "b", "c")

    if (-1 !in 0..list.lastIndex) {
        println("-1 is out of range")
    }
    if (list.size !in list.indices) {
        println("list size is out of valid list indices range, too")
    }
}
  • 범위를 반복함
fun main() {
    for (x in 1..5) {
        print(x)
    }
}
  • 또는 진행 이상
fun main() {
    for (x in 1..10 step 2) {
        print(x)
    }
    println()
    for (x in 9 downTo 0 step 3) {
        print(x)
    }
}

14. Collections

  • 컬렉션을 반복함
fun main() {
    val items = listOf("apple", "banana", "kiwifruit")
    for (item in items) {
        println(item)
    }
}
  • in 연산자를 사용하여 컬렉션에 개체가 포함되어 있는지 확인함
fun main() {
    val items = setOf("apple", "banana", "kiwifruit")
    when {
        "orange" in items -> println("juicy")
        "apple" in items -> println("apple is fine too")
    }
}
  • 람다식을 사용하여 컬렉션 필터링 및 매핑 :
fun main() {
    val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
    fruits
        .filter { it.startsWith("a") }
        .sortedBy { it }
        .map { it.uppercase() }
        .forEach { println(it) }
}

15. Nullable values and null checks

  • null 값이 가능할 때, 참조는 명시적으로 nullable로 표시되어야 하며, Nullable 형식 이름은 ?끝에 있음
  • 정수가 없으면 null 반환 : str
fun parseInt(str: String): Int? {
    // ...
}
  • nullable 값을 반환하는 함수 사용 :
fun parseInt(str: String): Int? {
    return str.toIntOrNull()
}

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 main() {
    printProduct("6", "7")
    printProduct("a", "7")
    printProduct("a", "b")
}
  • or
fun parseInt(str: String): Int? {
    return str.toIntOrNull()
}

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)
    
    // ...
    if (x == null) {
        println("Wrong number format in arg1: '$arg1'")
        return
    }
    if (y == null) {
        println("Wrong number format in arg2: '$arg2'")
        return
    }

    // x and y are automatically cast to non-nullable after null check
    println(x * y)
}

fun main() {
    printProduct("6", "7")
    printProduct("a", "7")
    printProduct("99", "b")
}

16. Type checks and automatic casts

  • 연산자는 표현식이 is 유형의 인스턴스인지 확인하며, 변경할 수 없는 지역 변수나 속성이 특정 유형에 대해 확인된 경우 명시적으로 캐스팅할 필요가 없음
fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }

    // `obj` is still of type `Any` outside of the type-checked branch
    return null
}

fun main() {
    fun printLength(obj: Any) {
        println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength(1000)
    printLength(listOf(Any()))
}fun getStringLength(obj: Any): Int? {
    if (obj !is String) return null

    // `obj` is automatically cast to `String` in this branch
    return obj.length
}

fun main() {
    fun printLength(obj: Any) {
        println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength(1000)
    printLength(listOf(Any()))
}
  • or
fun getStringLength(obj: Any): Int? {
    if (obj !is String) return null

    // `obj` is automatically cast to `String` in this branch
    return obj.length
}

fun main() {
    fun printLength(obj: Any) {
        println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength(1000)
    printLength(listOf(Any()))
}
  • else
fun getStringLength(obj: Any): Int? {
    // `obj` is automatically cast to `String` on the right-hand side of `&&`
    if (obj is String && obj.length > 0) {
        return obj.length
    }

    return null
}

fun main() {
    fun printLength(obj: Any) {
        println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength("")
    printLength(1000)
}
728x90
반응형

댓글