kotlin20 [Kotlin] object를 다루는 방법 Object를 다루는 방법 static 함수와 변수 Java public class JavaPerson { private static final int MIN_AGE = 1; public static JavaPerson newBaby(String name) { return new JavaPerson(name, MIN_AGE); } private String name; private int age; private JavaPerson(String name, int age) { this.name = name; this.age = age; } } Kotlin class Person private constructor(var name: String, var age: Int) { companion object Fa.. 2022. 7. 6. [Kotlin] 접근제어를 다루는 방법 접근제어를 다루는 방법 자바와 코틀린의 가시성 제어 자바의 접근 제어 public: 모든 곳에서 접근 가능 protected: 같은 패키지 또는 하위 클래스에서만 접근 가능 default: 같은 패키지에서만 접근 가능 private: 선언된 클래스 내에서만 접근 가능 코틀린의 접근 제어 public: 모든 곳에서 접근 가능 protected: 선언된 클래스 또는 하위 클래스에서만 접근 가능 internal: 같은 모듈에서만 접근 가능 private: 선언된 클래스 내에서만 접근 가능 코틀린에서는 패키지를 namespace를 관리하기 위한 용도로만 사용한다. 가시성 제어에는 사용되지 않는다. 모듈: 한 번에 컴파일 되는 kotlin 코드 자바의 기본 접근 지시어는 default이지만, 코틀린은 public.. 2022. 7. 6. [Kotlin] 클래스를 다루는 방법 클래스를 다루는 방법 클래스와 프로퍼티 Java public class JavaPerson { private final String name; private int age; public JavaPerson(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } Kotlin class Person1 constructor(name: String, age: Int) { val name: String = name; var age: Int.. 2022. 7. 6. [Kotlin] 함수를 다루는 방법 함수를 다루는 방법 함수 선언 문법 Java public int max(int a, int b) { if (a > b) { return a; } return b; } Kotlin fun max(a: Int, b: Int): Int = if (a > b) { a } else { b } fun maxV2(a: Int, b: Int) = if (a > b) a else b 함수의 문법은 Java와 다르다. 접근지시어 fun 함수이름(파라미터): 반환타입 {} body가 하나의 값으로 간주되는 경우 block을 없앨 수도 있고, block이 없다면 반환 타입을 없앨 수도 있다. {}를 없애고 = 를 사용할 수 있다. if else 문은 Expression이기 때문에 = 으로 대치 가능한 것. public은 생략.. 2022. 7. 6. [Kotlin] 예외를 다루는 방법 예외를 다루는 방법 try catch finally 구문 Java private int parseIntOrThrow(@NotNull String str) { try { return Integer.parseInt(str); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("주어진 %s는 숫자가 아닙니다.", str)); } } Kotlin fun parseIntOrThrow(str: String): Int { try { return str.toInt() } catch (e: NumberFormatException) { throw IllegalArgumentException("주어진 ${str}는 숫자가 .. 2022. 7. 6. [Kotlin] 반복문을 다루는 방법 반복문을 다루는 방법 for-each (향상된 for) 문 val numbers = listOf(1L, 2L, 3L) for (number in numbers) { println(number) } iterable이 구현된 타입이라면 모두 for-each문에 들어갈 수 있다. 하지만 자바에서 쓰던 : 대신에 in을 사용한다. for문 // 일반적인 for for (i in 1..3) { println(i) } // 내려가는 경우 for (i in 3 downTo 1) { println(i) } // 1, 3, 5 for (i in 1..5 step 2) { println(i) } Progression과 Range ..연산자: 범위를 만들어내는 연산자 IntRange는 IntProgression(등차수열)을.. 2022. 7. 6. [Kotlin] 조건문을 다루는 방법 조건문을 다루는 방법 if문 fun validateScoreIsNotNegative(score: Int) { if (score !in 0..100) { throw IllegalArgumentException("${score}는 의 범위는 0부터 100입니다.") } } if, else if, else문 모두 자바와 동일하다. Expression과 Statement fun getGrade(score: Int): String { return if (score >= 90) { "A" } else if (score >= 80) { "B" } else if (score >= 70) { "C" } else { "F" } } Statement: 프로그램의 문장, 하나의 값으로 도출되지 않는다. Expression: .. 2022. 7. 6. [Kotlin] 연산자를 다루는 방법 연산자를 다루는 방법 단항 연산자, 산술 연산자 public class JavaMoney implements Comparable{ private final long amount; public JavaMoney(long amount) { this.amount = amount; } @Override public int compareTo(@NotNull JavaMoney o) { return Long.compare(this.amount, o.amount); } } val money1 = JavaMoney(2_000L) val money2 = JavaMoney(1_000L) // compareTo를 자동 호출한다. if (money1 > money2) { println("money1이 money2보다 금액이 큽.. 2022. 7. 5. [Kotlin] Type을 다루는 방법 Type을 다루는 방법 기본타입 val number1 = 3 // 명시적으로 타입을 변환해야 한다. val number2: Long = number1.toLong() // nullable 의 경우에는 적절한 처리가 필요하다. val number1: Int? = 3 val number2: Long = number1?.toLong() ?: 0L 코틀린에서는 선언된 기본값을 보고 타입을 추론한다. 3: Int, 3L: Long, 3.0: Double, 3.0f: Float Java에서 기본 타입간의 변환은 암시적으로 이루어지지만 (int Integer) Kotlin에서는 기본 타입간의 변환은 명시적으로 이루어져야 한다. 그렇기 때문에 toLong()과 같이 명시적 형변환이 필요하다. 타입 캐스팅 fun pri.. 2022. 7. 5. 이전 1 2 3 다음