brunch

You can make anything
by writing

C.S.Lewis

by 이승현 Jan 26. 2022

Kotlin 면접 질문 #01

Kotlin interview questions

Journaldev

https://www.journaldev.com/20567/kotlin-interview-questions




Question #01

What’s the Target Platform of Kotlin? How is Kotlin-Java interoperability possible?

(Kotlin 의 타겟 플랫폼은? Kotlin-Java 간 상호 운용성은 어떻게 가능한가?)


Answer


JVM(Java Virtual Machine)이 Kotlin 의 타겟 플랫폼이다. 

Kotlin 은 컴파일 시 바이트 코드를 생성하므로, Java와 100% 상호 운용 가능하다.

따라서 Java에서 Kotlin 코드를 호출할 수 있으며 그 반대의 경우도 마찬가지입니다.




Question #02

How do you declare variables in Kotlin? How does the declaration differ from the Java counterpart?

(Kotlin 의 변수 선언 방법은? Java 와 차이점은?)


Answer

// Java
String s = "Java String";
int x = 10;


// Kotlin
val s: String = "Kotlin String"
var x = 10


Kotlin에서 선언은 val 과 var 로 시작하고 그 뒤에 Type 이 옵니다.

Kotlin은 Type 추론을 사용하여 Type 을 자동으로 감지할 수 있습니다.




Question #03

What’s the difference between val and var declaration? How to convert a String to an Int?

(val 와 var 선언의 차이점은? String 을 Int 로 변환하는 방법은?)


Answer


val 는 변경할 수 없습니다. 

자바의 final modifier 와 같습니다.


var 는 재할당할 수 있습니다. 

재할당된 값은 동일한 Type 이어야 합니다.


fun main(args: Array<String>) {
     var x = 5
     x = "6".toInt()
}


toInt() 함수를 이용해서 String 을 Int 로 변환할 수 있다.




Question #04

What’s Null Safety and Nullable Types in Kotlin? What is the Elvis Operator?

(Null Safety 와 Nullable Types 이란? Elvis 연산자 란?)


Answer


Kotlin 은 Null Pointer Exception(NPE) 를 방지하기 위해, String?, Int?, Float? 같은 nullable 타입들을 이용합니다.

이러한 타입들은 null 값을 가질 수 있습니다.


Elvis 연산자는 이런 nullable 타입들을 안전하게 값을 이용할 수 있도록 사용할 수 있습니다.

nullable 타입 뒤에 ?: 로 표시하며, nullable 타입의 값이 null 일 경우 오른쪽 값을 이용합니다.

var str: String?  = "JournalDev.com"
var newStr = str?: "Default Value"        //  JournalDev.com
 
str = null
newStr = str?: "Default Value"              // Default Value




Question #05

What’s a const? How does it differ from a val?

(const? val 와 다른점은?)


Answer


기본적으로 val properties 는 runtime 에 설정(set)됩니다.

const modifier 를 붙이면, val 는 compile-time 상수가 됩니다.


const 는 var 에 쓸 수 없습니다.

그리고 지역 변수에도 쓸 수 없습니다.

toInt()

const val str = "CONSTANT STRING"

// Compile error
// Modifier 'const' is not applicable to 'var'
const var str2 = "COMPILE ERROR"

fun main(args: Array<String>) {

    // Compile error
    // Modifier 'const' is not applicable to 'local variable'
    const val x = 10 
}




Question #06

How is !! different from ?. in unwrapping the nullable values? Is there any other way to unwrap nullable values safely?

(!! 와 ? 의 차이점은? nullable 값을 안전하게 이용할 수 있는 다른 방법은?)


Answer


!! 는 nullable 타입의 값을 강제로 가져오기 위해 쓰입니다.

만약 값이 null 이면, 런타임 crash 가 발생합니다.

따라서 값이 null 이 아니라고 확신할 때만 이용해야 합니다.


? 는 안전하게 nullable 타입의 값을 가져올 수 있는 Elvis 연산자 입니다.


let 을 이용해서 안전하게 nullable 타입의 값을 가져올 수 있습니다.


fun main(args: Array<String>) {
    var str: String? = "JournalDev.com"
    str?.let { println(str) }        // JournalDev.com

    str = null
    str?.let { println(str) }        // DO NOTHING
}




Question #07

What’s the difference between == and === operators in Kotlin?

(== 와 === 의 차이점은?)


Answer


== : value 비교

=== : reference 비교




Question #07

Does the following inheritance structure compile?

(아래 상속 구조는 컴파일이 되는가?)


class A {

}

class B : A() {

}


Answer


안된다. open 을 붙여야 한다.


open class A {

}

class B: A() {

}




Question #08

What are the types of constructors in Kotlin? How are they different?

(Kotlin 에서 생성자 타입들은? 어떤 차이가 있는가?)


Answer


Primary

class header 에 정의한다.

logic 을 가질 수 없다.

class 당 하나만 있다.


Secondary

class body 에 정의한다.

Primary 생성자가 있는 경우, 반드시 delegate 해야 한다.

logic 을 가질 수 있다.

class 당 1개 이상 있을 수 있다.


class User(name: String, isAdmin: Boolean) { // primary constructor

    // secondary constructor
    constructor(name: String, isAdmin: Boolean, age: Int) :this(name, isAdmin) {         this.age = age
    }

}




Question #09

What’s init block in Kotlin?

(Kotlin 에서 init block 이란?)


Answer


init 은 Kotlin 의 초기화(initialiser) block 이다.


primary 생성자가 인스턴스화되면 실행된다.

secondary 생성자가 호출되면, priamary 생성자 다음에 실행된다.




Question #10

What’s the type of arguments inside a constructor?

(생성자 내부 argument 들의 타입은?)


Answer


var 로 지정하지 않는 한, 기본적으로 val 이다.




Question #11

What is the equivalent of switch expression in Kotlin? How does it differ from switch?

(Kotlin 에서 switch 표현문에 해당하는 것은? Java 와 차이점은?)


Answer


when 은 Kotlin 의 switch 에 해당합니다.

when 의 기본 상태는 else 를 사용하여 표현됩니다.


when (num) {         
    0..4 -> print("value is 0")         
    5 -> print("value is 5")         
    else -> {             
        print("value is in neither of the above.")
     }
}




Question #12

What are data classes in Kotlin? What makes them so useful? How are they defined?

(data 클래스란? 장점은? 어떻게 정의하나?)


Answer


Java 에서는 data 를 저장하는 class 를 생성하기 위해, 변수마다 getter/setter 를 설정하고, toString(), hash(), copy 함수를 직접 override 해야 한다.


Kotlin 에서는 data 라는 keyword 를 class 앞에 추가만하면, 자동으로 위와 같은 것들을 생성해준다.


data class Book(var name: String, var authorName: String)

fun main(args: Array<String>) {
     val book = Book("Kotlin Tutorials", "Anupam")
 }




Question #13

What are destructuring declarations in Kotlin?

(destructuring declarations 이란?)


Answer


Destructuring Declarations 는 objects/arrays에 저장된 여러 값들을 변수에 대입하는 현명한 방법입니다.


data class Book(var name: String, var authorName: String)

fun main(args: Array<String>) {

    val book = Book("Kotlin tutorials", "Anupam")
    var (n, a) = book
    println(n)        // Kotlin tutorials
    println(a)        // Anupam
}




Question #14

What’s the difference between inline and infix functions?

(inline 과 infix 함수의 차이점은?)


Answer


Inline functions  는 호출된 익명 함수(anonymous functions)/람다식(lambda expressions)에 대한 객체(object) 할당을 방지하여메모리 오버헤드를 줄이는데 이용됩니다.


대신 런타임에 호출하는 함수에 해당 함수 body 를 제공합니다.

이로인해 바이트코드의 크기는 약간 증가하지만 메모리를 많이 절약합니다.


fun main(args: Array<String>) {
    inlineFunctionExample(
        { println("Inline Functions") },
        { println("Instead of object creation it copies the code.") }
    )
}

inline fun inlineFunctionExample(myFunction: () -> Unit, another: () -> Unit) {
    myFunction()        // Inline Functions
    another()               // Instead of object creation it copies the code.
}


Infix functions 는 두 개의 변수 가운데 오는 함수를 말한다.

이로인해 코드가 더 간결해진다.

(참고로 오직 하나의 매개변수만 쓸 수 있다.)


fun main(args: Array<String>) {
    val b = Numbers()
    b addNumber 5

    println(b)        // 15
}

class Numbers() {
    var x = 10

    infix fun addNumber(num: Int) {
        this.x = this.x + num
    }
}




Question #15

What’s the difference between lazy and lateinit?

(lazy 와 lateinit 의 차이점은?)


Answer


둘 다 property 초기화를 지연하는 데 이용합니다.


lateinit 은 var 에 쓰입니다.

나중에 var 값을 설정합니다.


lazy 는 val 에 쓰입니다.

필요할 때 런타임에 생성됩니다.


val x: Int by lazy { 10 }

lateinit var y: String




Question #16

How to create Singleton classes?

(싱글톤 클래스 생성 방법은?)


Answer


object 키워드를 이용해서 생성합니다.

별도의 생성자는 없고, init 함수를 통해 초기화할 수 있습니다.


object MySingletonClass




Question #17

Does Kotlin have the static keyword? How to create static methods in Kotlin?

(static 키워드를 가지고 있는가? 어떻게 static method 를 생성할 수 있는가?)


Answer


Kotlin 은 static 키워드가 없다.


static method 를 생성하기 위해서 companion object 를 써야한다.


// Java

class A {   
    public static int returnMe() { 
        return 5;
    }



// Kotlin
class A {   
    companion object {      
        fun a() : Int = 5   
    }
}
매거진의 이전글 안드로이드 개발자 이직 면접 (지인)

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari