본문 바로가기
Language/Kotlin

kotlin 뽀개기_02) Basic syntax

by 태하팍 2025. 12. 1.
반응형


자바 개발자라면 자바랑 비교해가면서 학습하면 더 좋을것 같습니다.
놀이터는 요기! https://play.kotlinlang.org/

Package definition and imports

kotlin

package my.demo
import kotlin.text.*
// ...

Java

package com.easy.nstroe.service

import java.util.*;

별반 다를께 없음!


Program entry point

kotlin

fun main() {
    println("Hello world!")
}

// String argument는 아래처럼 사용
fun main(args: Array<String>) {
    println(args.contentToString())
}

Java(=psvm단축기로 메인을 바로 만들수 있음!)

public class EasyNaverStoreApplication {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

kotlin

print("Hello ")
print("world!")

println("Hello world!")
println(42)

Java(=sout 단축기로 쉽게~)

System.out.print("Taeha");

System.out.println("Park!");

Read from the standard input

kotlin이 매우 간단하다. readIn()이면 끝~

kotlin

// Prints a message to request input
println("Enter any word: ")

// Reads and stores the user input. For example: Happiness
val yourWord = readln()

// Prints a message with the input
print("You entered the word: ")
print(yourWord)
// You entered the word: Happiness

Java

Scanner sc = new Scanner(System.in);
String s = sc.nextLine();

Functions

Kotlin

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

fun main() {
    print("sum of 3 and 5 is ")
    println(sum(3, 5))
}

Java

public Map<String, Object> getUserInfo(String accessToken) {
	// 블라블라
}

int a 스타일이 자바라면 a: Int는 kotlin style~
return도 자바는 왼쪽에 있지만 코틀린은 오른쪽에! : Int

또한 코틀린은 = a+b처럼 사용도 가능

fun sum(a: Int, b: Int) = a + b

fun main() {
    println("sum of 19 and 23 is ${sum(19, 23)}")
}

코틀린은 : Unit라는게 있는데 자바에서는 void랑 같은 겁니다.
리턴이 없을 때 사용 합니다.

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)
}

Variables

kotlin에서 변수는 val과 var가 있습니다.
val은 immutable~!! read only local variables! 그래서 재할당 안돼쥬!
var은 일반변수처럼 mutable 합니다. 그래서 아래와 같이 값이 변합니다.

fun main() {
    // Declares the variable x and initializes it with the value of 5
    var x: Int = 5
    // Reassigns a new value of 6 to the variable x
    x += 1
    
    println(x)
}

// 답은? 6

Creating classes and instances

class는 자바와 동일하게 class키워드를 사용해서 만듭니다.

class Shape
// 코틀린
calss Rectangle
뒤에 (val height: Double, val length: Double) <-- 기본생성자
아래의 { .. } 부분은 뭔가 로직이 들어가는 부분처리(아래 자바문법과 비교하면 쉽게 이해 가능!) 
{
    val perimeter = (height + length) * 2
}


/********코틀린*********/

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


/********자바*********/
public class Rectangle {
    public final double height;
    public final double length;
    public final double perimeter;

    public Rectangle(double height, double length) {
        this.height = height;
        this.length = length;
        this.perimeter = (height + length) * 2;
    }
}

자바는 new 연산자로 객체 생성시 기본 생성자(primary constructor가 발동!
코틀린은 new없이 Rectangle(5.0, 2.0) 호출 시 생성자 자동호출!
즉, 객체 생성(=val rectangle = Rectangle(5.0, 2.0))

class Rectangle(val height: Double, val length: Double) {
    val perimeter = (height + length) * 2 
}
fun main() {
    val rectangle = Rectangle(5.0, 2.0)
    println("The perimeter is ${rectangle.perimeter}")
}

상속은 어떻게?

: 는 상속을 의미 합니다.(= class Rectangle() : Shape())
자바라면 class Rectangle extends Shape

open class Shape

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

코틀린은 기본적으로 기본값이 final(상속금지) 상태라서 open class Shape처럼 이 클래스는 상속해도 된다고 알려줘야 합니다.
그리고 상속할 때 :Shape가 아니라 :Shape()의 형태인데 이것은 부모의 생성자도 호출하라는 뜻 입니다.

그럼 implement는 어떻게 하나?
kotlin은 implement 키워드가 없으며 구현할 때도 마찬가지로 : 로 합니다.
단, 차이는 생성자 호출 여부 입니다.

interface Clickable {
    fun click()
}

class Button : Clickable {
    override fun click() {
        println("Button clicked")
    }
}

자바라면?

class Button implements Clickable { }

그럼 상속과 구현 2가지를 사용한다면??
: Shape(), Clickable <-- 이런식으로 사용 합니다.

open class Shape

interface Clickable {
    fun click()
}

class Rectangle(height: Double, length: Double)
    : Shape(), Clickable {

    override fun click() {
        println("clicked")
    }
}

String templates

kotlin은 $라는게 있어서 편하게 문자열과의 결합이 가능합니다. 요런 기능을 String templates라고 부릅니다.
자바로 구현하려면 빡셉니다.
String templates은 문자열+변수+로직(함수호출+계산) 등을 한 줄안에서 자연스럽게 작성할 수 있습니다.

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) // a was 1, but now is 2
}

for loop

for loop에는 2가지 방법이 있습니다.

값만 가져와서 뿌려줄땐

fun main() {
    val items = listOf("apple", "banana", "kiwifruit")
    for (item in items) {
        println(item)
    }
}

/* result **
apple
banana
kiwifruit
*/

.indices로 인덱스구해서 출력할 수 있습니다.

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

/* result ***
item at 0 is apple
item at 1 is banana
item at 2 is kiwifruit
/*

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++
    }
}

참고 : https://kotlinlang.org/docs/basic-syntax.html

대충 느낌이 왔다면 프로젝트를 만들어서 적용하면서 필요한것 위주로 찾아서 익히면 더 좋을것 같습니다.

반응형