안드로이드 탐구 : Kotlin & Java

Skele·2025년 2월 13일
1

What is Kotlin?


A programming language targeting the Java platform. Kotlin is concise, safe, pragmatic, and focused on interoperability with Java code.


Kotlin in Action - 1.1

코틀린은 자바 플랫폼을 대상으로한 프로그래밍 언어로, 간결하고 안전하며 실용적이면서 자바와의 상호호환에 중점을 두고 있다.

Kotlin 예시 코드

data class Person(val name: String, val age: Int? = null) //'data' 클래스, Nullable Type의 존재

fun main(args: Array<String>) {

	val persons = listOf(Person("Alice"), Person("Bob", age = 29)) //Named Argument
    
	val oldest = persons.maxBy { it.age ?: 0 } // Lambda, Elvis 연산자
    
	println("The oldest is: $oldest") // String 템플릿
    
}

// The oldest is: Person(name=Bob, age=29)

Primary Traits


The primary goal of Kotlin is to provide a more concise, more productive, safer alternative to Java that’s suitable in all contexts where Java is used today.


Kotlin in Action - 1.2.1

Target Platform


In most of these places, using Kotlin can help developers achieve their goals with less code and fewer annoyances along the way.

The most common areas to use Kotlin are these:

  • Building server-side code (typically, backends of web applications)
  • Building mobile applications that run on Android devices

But Kotlin works in other contexts as well.
In addition to Java, Kotlin can also be compiled to JavaScript, allowing you to run Kotlin code in the browser.


Kotlin in Action - 1.2.1

코틀린은 자바가 사용되는 환경과 상호운용이 가능할 뿐만 아니라, 브라우저에 사용되는 자바스크립트로도 컴파일 될 수 있다.

Statically Typed


Just like Java, Kotlin is a statically typed programming language. This means the type of every expression in a program is known at compile time, and the compiler can validate that the methods and fields you’re trying to access exist on the objects you’re using.


Kotlin in Action - 1.2.2

자바와 동일하게, 코틀린은 정적 타입을 사용한다.

Dynamically Typed languages let you define variables and functions that can store or return data of any type and resolve the method and field references at runtime. This allows for shorter code and greater flexibility in creating data structures. But the downside is that problems like misspelled names can’t be detected during compilation and lead to runtime errors.

동적 타입 언어들이 짧은 코드와 유연성을 가지지만, 컴파일 시에 오타를 검출해낼 수 없어서 런타임 오류로 이어질 수 있다는 위험성이 존재한다.

Benefits of Statically Typed Languague

Following are some of the benefits of static typing:

  • Performance- Calling methods is faster because there’s no need to figure out at runtime
    which method needs to be called.
  • Reliability- The compiler verifies the correctness of the program, so there are fewer chances for crashes at runtime.
  • Maintainability- Working with unfamiliar code is easier because you can see what kind of objects the code is working with.
  • Tool support- Static typing enables reliable refactorings, precise code completion, and other IDE features.

이러한 정적 타입의 장점으로는

  • 성능 : 어느 메소드가 호출되어야하는지 런타임 중에 결정할 필요가 없다.
  • 신뢰성 : 컴파일러가 검증을 해주므로 런타임에 심각한 오류가 생길 가능성이 적다.
  • 유지보수성 : 처음보는 코드더라도 개발자가 타입을 유추할 필요가 없다.
  • 도구 지원 : IDE가 지원하는 안정적인 리팩토링과 정확한 코드완성을 가능케한다.

하지만 단점으로, 이러한 정적 타입 언어는 명시적으로 코드에 타입을 지정해야하기 때문에 코드가 불필요하게 길어지는 경우가 생긴다.

Deference between Java

On the other hand, in contrast to Java, Kotlin doesn’t require you to specify the type of every variable explicitly in your source code. In many cases, the type of a variable can automatically be determined from the context, allowing you to omit the type declaration.

그러나 자바와는 달리, 명시적으로 타입을 코드에 작성할 필요는 없다. 컴파일러가 맥락을 통해 타입을 추론해서 지정해주기 때문이다.

The most important of those is Kotlin’s support for nullable types, which lets you write more reliable programs by detecting possible null pointer exceptions at compile time.
Another new thing in Kotlin’s type system is its support for functional types.

또한 코틀린은 Null Pointer Exception을 보다 안정적으로 관리하기 위해 Nullable Type을 지원하고, 또한 함수 타입을 지원한다.

Functional and Object-oriented


The key concepts of functional programming are as follows:

  • First-class functions- You work with functions (pieces of behavior) as values. You can store them in variables, pass them as parameters, or return them from other functions.
  • Immutability- You work with immutable objects, which guarantees that their state can’t change after their creation.
  • No side effects- You use pure functions that return the same result given the same inputs and don’t modify the state of other objects or interact with the outside world.

Kotlin in Action - 1.2.3

함수형 프로그래밍의 특징으로는

  • 일급 함수 : 함수를 변수에 넣거나 매개변수로 넘기거나 반환하는 값으로 취급한다.
    • 간결한 코드를 작성할 수 있다.
  • 불변 : 객체가 생성 이후에 변경되지 않음을 보장할 수 있다.
    • 멀티 스레드 환경에서 불변객체로 안정성을 보장할 수 있다.
  • 부수효과 없음 : 외부에 영향을 주지 않고 입력에 따라 같은 출력을 주는 함수를 사용한다.
    • 외부에 의존적이지 않기에 테스트 환경을 만들기 용이하다.

Kotlin has a rich set of features to support functional programming from the get-go. These include the following:

  • Functional types, allowing functions to receive other functions as parameters or return other functions
  • Lambda expressions, letting you pass around blocks of code with minimum boilerplate
  • Data classes, providing a concise syntax for creating immutable value objects
  • Arich set of APIs in the standard library for working with objects and collections in the functional style

이렇게 함수형 프로그래밍을 지원하기 위해 코틀린은 다양한 지원을 해준다.

  • 함수 타입
  • 람다
  • 데이터 클래스
  • 표준 라이브러리에 포함된 풍부한 API

Difference between Java

Generally speaking, the functional style can be used with any programming language, including Java, and many parts of it are advocated as good programming style. But not all languages provide the syntactic and library support required to use it effortlessly.

자바 또한 함수형 프로그래밍을 사용할 수 있지만, 이를 쉽게 사용하기 위한 지원을 얼마나 하느냐의 차이가 있다고 볼 수 있다.

Characteristic


When we talk about Kotlin, we like to say that it’s a pragmatic, concise, safe language with a focus on interoperability.

코틀린은 실용적이고 간결하며 안전하면서도 상호운용성에 중점을 두고 있다고 한다.
하나씩 알아보도록 하자.

Pragmatic


Being pragmatic means a simple thing to us: Kotlin is a practical language designed to solve real-world problems.

Kotlin also is not a research language. We aren’t trying to advance the state of the art in programming language design and explore innovative ideas in computer science.
Instead, whenever possible, we’re relying on features and solutions that have already appeared in other programming languages and have proven to be successful. This reduces the complexity of the language and makes it easier to learn by letting you rely on familiar concepts.


Kotlin in Action - 1.4.1

실용적이란 말은 코틀린이 현실의 문제해결을 위해 디자인되었다는 뜻이다.
따라서 코틀린은 실험적인 언어가 아니라 다른 언어의 문제점과 해결방법을 참고하여 언어의 복잡성을 줄이고 익숙하게 만들어 쉽게 배울 수 있도록 만들어졌다.

Kotlin doesn’t enforce using any particular programming style or paradigm. As you begin to study the language, you can use the style and techniques that are familiar to you from your Java experience.

코틀린은 강제하는 스타일이 없다. 따라서 쓰던 자바 프로그래밍 스타일을 그대로 써도 된다.

Another aspect of Kotlin’s pragmatism is its focus on tooling. A smart development environment is just as essential for a developer’s productivity as a good language; andbecause of that, treating IDE support as an afterthought isn’t an option. In the case of Kotlin, the IntelliJ IDEA plug-in was developed in lockstep with the compiler, and language features were always designed with tooling in mind.

코틀린 컴파일러는 IDEA 플러그인과 같이 개발되어 여러 개발도구를 지원한다. 이러한 지원 도구는 코드 작성에 있어 패턴을 파악하고 보다 코틀린 스타일의 간결한 코드를 제안하는 등 코틀린에 친숙해지도록 한다.

Concise


The simpler and more concise the code is, the faster you’ll understand what’s going on. Of course, good design and expressive names play a significant role here. But the choice of the language and its conciseness are also important. The language is concise if its syntax clearly expresses the intent of the code you read and doesn’t obscure it with boilerplate required to specify how the intent is accomplished.


Kotlin in Action - 1.4.2

코드가 단순하고 간결할수록 보다 빠르게 이해할 수 있다.
여기서 언어가 간결하다는 것은 문법이 코드의 의도를 표현하면서 보일러 플레이트 코드가 이를 모호하게 만들지 않는다는 것이다.

In Kotlin, we’ve tried hard to ensure that all the code you write carries meaning, and isn’t just there to satisfy conventions. A lot of the standard Java boilerplate, such as getters, setters, and the logic for assigning constructor parameters to fields, is implicit in Kotlin and doesn’t clutter your source code.

코틀린은 그렇기에 코드가 의미를 전달할 수 있으면서 표준 자바의 보일러플레이트들이 내장되어 소스코드를 복잡하게 만들지 않도록 하였다.

Java

public class User {
    private String name;
    
    public User(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Kotlin

data class User(var name: String)

At the same time, Kotlin doesn’t try to collapse the source code to the smallest number of characters possible. For example, even though Kotlin supports operator overloading, users can’t define their own operators. Therefore, library developers can’treplace the method names with cryptic punctuation sequences. Words are typically easier to read than punctuation and easier to find documentation on, even if they’re somewhat longer.

그러면서도 코틀린은 너무 짧은 코드는 지양하며 가독성이 낮아지지 않도록 하였다.
코틀린은 새로운 연산자 정의를 지원하지 않음으로서 메소드가 아닌 의미불명의 연산자의 나열을 사용하지 못하도록 방지했다.

Safe


In general, when we speak of a programming language as safe, we mean its design prevents certain kinds of errors in a program.

보통 안전한 언어란, 그 언어의 구조 덕분에 개발함에 있어서 오류가 적은 것을 말한다.

Kotlin strives to remove the NullPointerException from your program. Kotlin’s type system tracks values that can and can’t be null and forbids operations that can lead to a NullPointerException at runtime.


Kotlin in Action - 1.4.3

코틀린은 Null이 될 수 있는 값인지 아닌지 추적하며 런타임에 NullPointerException이 나지 않도록 방지한다.

val s: String? = null // Nullable
val s2: String = "" //Not-null

Another type of exception that Kotlin helps avoid is the ClassCastException. It happens when you cast an object to a type without first checking that it has the right type. In Kotlin, on the other hand, the check and the cast are combined into a single operation: once you’ve checked the type, you can refer to members of that type without any additional casts.

코틀린은 타입 체크를 하지 않아 생기는 ClassCastException을 보다 쉽게 처리할 수 있도록 지원한다.

Java

if (obj instanceof String) {
    String str = (String) obj; // 타입 체크 후 캐스팅
    System.out.println(str.length());
}

Kotlin

if (obj is String) {
    println(obj.length) // 추가 캐스팅 없이 안전하게 사용 가능
}

Interoperable


Regarding interoperability, your first concern probably is, "Can I use my existing libraries?" With Kotlin, the answer is, "Yes, absolutely." Regardless of the kind of APIs the library requires you to use, you can work with them from Kotlin. You can call Java methods, extend Java classes and implement interfaces, apply Java annotations to your Kotlin classes, and so on.


Kotlin in Action - 1.4.4

"코틀린과 자바 라이브러리를 같이 사용해도 되나요?" 라는 질문에 답은 "당연하다" 라는 것이다.

Kotlin classes and methods can be called exactly like regular Java classes and methods. This gives you the ultimate flexibility in mixing Java and Kotlin code anywhere in your project.

코틀린 클래스와 메소드는 자바의 그것과 동일하게 사용가능하다.

Another area where Kotlin focuses on interoperability is its use of existing Java libraries to the largest degree possible. For example, Kotlin doesn’t have its own collections library. It relies fully on Java standard library classes, extending them with additional functions for more convenient use in Kotlin.

코틀린은 자바 라이브러리를 최대한 활용하여 상호운영성에 힘을 주었다.

profile
Tireless And Restless Debugging In Source : TARDIS

0개의 댓글