기본 문법 간단 리뷰

2021. 8. 11. 16:25Kotlin/문법

반응형
package com.example.studykotlin

fun main() {
    val tag = "[main]";
    println("Hello world");

    var x : Int = 10;
    var y = 20; // 보통은 type은 생략

    var str = "Hello"; // String

    var isMarried = true; // boolean

    // kotlin에서는 선언과 함께 초기화하는 것을 추구
    // primitive type은 대문자로 시작

    val b = 10; // 상수

    x = 40; // 변수는 변경할 수 있음
    //b = 40; // 상수는 변경할 수 없음

    println(str+str);
    println("$str $str"); // 문자열 템플릿
    println("${x+b} $str ");
    println(myMetohd(x, b));
    println(myMethodSecond(x, b));


    val items = arrayOf(1,2,3,4,5); // kotlin에서는 변수보단 상수를 선호
    print(items);

    val itemList = listOf<Int>(1,2,3,4,5); // 보통은 array보단 list를 사용, 제네릭 생략 가능
    print(itemList); // 출력시 list는 내부 항목이 보임

    //itemList.add(6) // 기본적으로 list는 불변
    val itemListSecond = arrayListOf(1,2,3,4,5);
    itemListSecond.add(6);
    print(itemListSecond);

    itemListSecond.remove(6);
    print(itemListSecond);

    itemListSecond.set(1,8);
    itemListSecond[1] = 8; // 위와 같은 의미

    if(x % 2 == 0){
        print("짝수");
    }

    val isEven = if(x%2==0) print("짝수") else print("홀수"); // if를 식으로 사용

    for(i in 0..9){
        println(i);
    }

    for(i in itemListSecond){
        print(i);
    }

    val t = when(x){
        1 -> print("1");
        2 -> print("2");
        3,4,5 -> print("3");
        in 6..20 -> print("4");
        !in 6..20 -> print("5");
        else -> print(x);
    }

    val person = Person(str); // new 키워드 필요 없음, type 생략
    print(person.name); // person.getName();
    // person.name = "김미진"; // name이 var 아니기 때문에 불가

    val data = Data(str, str, 10);
    print(data); // 일반적으로 toString(), getter/setter, equals(), hashCode() 정의한 것으로 봄


    print(str.myFunc()); // 확장함수를 본 클래스에 있는 메소드처럼 사용 가능

    val item = Item(); // java와 호환 가능
    print(item);
    print(item.name);

}

fun myMetohd(a : Int, b : Int) : Int { // return type이 뒤에 명시됨
    return a+b;
}

fun myMethodSecond(a : Int, b : Int) : Int = a+b // 식처럼 함수 선언 가능


class Person(val name : String) { //기본 접근자가 public, 생성자와 함께 선언, 프로퍼티의 읽기전용/쓰기 설정
    init { // 생성자의 역할 + 초기 기능 선언
        print(name)
    }
}

data class Data(
    val name : String,
    val address : String,
    val age : Int
)

fun String.myFunc() : Int {
    // final class인 String을 확장하는 것이 kotlin에서는 가능하다
    return this.length
}








import android.view.View
import com.example.studykotlin.R

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // extends 대신 :로 대체가 되었고,
        // 부모 class의 경우 생성자를 같이 호출(AppCompatActivity())
        // 인터페이스의 경우 생성자 표식 없음

        // var x : String = null // String은 null 불가능
        var y :  String? = null // String?은 null 가능

        val button = Button(this)
        button.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                print("hello");
            }
        }) // java style, 인터페이스 안에 메소드가 여러개일 때 빼고 잘 사용하지 않음
        button.setOnClickListener{print("hello")};
        // 람다식은 메소드가 하나인 인터페이스 구현에 사용되며,
        // 해당 인터페이스에 넘겨지는 인자를 넘겨주면 되는데
        // button.setOnClickListener(new View.OnClickListener()) 처럼 인자값이 없고,
        // button.setOnClickListener(() -> {print("hello")}); 해당 객체는 람다식으로 변형되고,
        // button.setOnClickListener(){print("hello")}
        // button.setOnClickListener{print("hello")} 함수에서 람다식이 마지막에 오는 인자라면 함수 밖으로 빼서 표현할 수 있다.

    }
}
반응형

'Kotlin > 문법' 카테고리의 다른 글

by  (0) 2022.02.24
Class 상속  (0) 2021.04.23
Class 생성과 위임  (0) 2021.04.23