본문 바로가기

기술면접

Java와 Kotlin 차이

 

1. JAVA

  • 객체 지향 지원
  • 할당되는 값으로부터 컴파일러가 타입을 추론 (Java 10 이후 가능)
  • Null 할당 불가 (런타임에 Null point 예외 발생)
  • val 지원 X

 

2. Kotlin

  • 객체 지향 + 함수형 모두 지원
    • 함수형 : 람다, 고차 함수 (filter, forEach)
  • 할당되는 값으로부터 컴파일러가 타입을 추론
  • Null 할당이 가능한 타입 미리 선언 가능
  • Null Point 예외를 컴파일 시점에서 미리 방지  (Nullable이 아닌 변수에 null 넣으면 컴파일 에러 발생)
  • 기본형 타입마저 클래스로 존재 (Nullable 위해)
var nullableInt: Int? = null // Nullable Int 변수
var nonNullableInt: Int = 42 // Non-nullable Int 변수

Int는 클래스이며 Int?는 Nullable한 버전의 Int
-> 이런 구조는 Nullable을 명시적으로 다룰 수 있도록 도와줌

 

2.1 장점

  • 코드의 양이 줄어들고 간결 (생성자, 게터, 세터 묵시적 제공)
  • 다양한 표준 라이브러리 → 반복되는 코드 줄일 수 있음
  • 자바와 호환됨, kotlin에서 API 활용 가능

 

3. Java 와 Kotlin 코드 차이

1) 생성자

  • kotlin : 프로퍼티 선언과 초기화 동시에
  • java : 프로퍼티 선언, 초기화 따로
class PageOptionRequest(
    val actionType: String,
    val os: String? = "ios"
)
@Getter
@Builder
@AllArgsConstructor
public class PageOptionRequest {
  @NotNull(message = "actionType is required!")
  private String actionType;
  @Nullable
  private String os;  
 
  public PageOptionRequest(String actionType) {
    this.actionType = actionType;
    this.os = "ios";
  }
}

 

2) data class

  • java에서는 명시적으로 제공하는 data class 없음
  • kotlin은 toString, hashCode(), equals(), copy() 메소드 기본으로 제공
data class PageOptionRequest(val actionType: String, val os: String)
//유사하게 만든 data class

import java.util.Objects;

public class PageOptionRequest {
    private final String actionType;
    private final String os;

    public PageOptionRequest(String actionType, String os) {
        this.actionType = actionType;
        this.os = os;
    }

    public String getActionType() {
        return actionType;
    }

    public String getOs() {
        return os;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PageOptionRequest that = (PageOptionRequest) o;
        return Objects.equals(actionType, that.actionType) &&
               Objects.equals(os, that.os);
    }

    @Override
    public int hashCode() {
        return Objects.hash(actionType, os);
    }

    @Override
    public String toString() {
        return "PageOptionRequest{" +
               "actionType='" + actionType + '\'' +
               ", os='" + os + '\'' +
               '}';
    }
}

 

3) null 처리

class OptionRequest(
    val user_id: String,
    val os: String? = "ios"
)
public class OptionRequest {
  @NotNull(message = "user_id is required!")
  private String user_id;
  @Nullable
  private String os;  
}

 

 

출처: https://juhi.tistory.com/72 [Read me:티스토리]

'기술면접' 카테고리의 다른 글

Kotlin에서 Null 처리 방법  (0) 2024.01.19
비동기 프로그래밍  (1) 2024.01.04
예외  (1) 2024.01.04
Kotlin 정적 타입 언어  (1) 2024.01.04