코틀린은 JetBrains의 최신 JVM 프로그래밍 언어입니다. Google은 코틀린을 Android 개발의 공식 언어로 지정했습니다. 개발자들은 코틀린이 자바 프로그래밍에서 마주치는 문제를 해결한다고 말합니다. 저는 많은 코틀린 튜토리얼을 작성했고 여기서 중요한 코틀린 인터뷰 질문을 제공하고 있습니다.
코틀린 인터뷰 질문
여기에 코틀린 인터뷰 질문과 답변을 제공하여 코틀린 인터뷰에 도움이 될 것입니다. 이 코틀린 인터뷰 질문은 초보자뿐만 아니라 경험있는 프로그래머들에게도 좋습니다. 코딩 문제도 있어 코딩 기술을 갈고 닦을 수 있습니다.
-
코틀린의 대상 플랫폼은 무엇인가요? 코틀린-자바 상호 운용성은 어떻게 가능한가요?
자바 가상 머신(JVM)이 코틀린의 대상 플랫폼입니다. 코틀린은 자바와 100% 상호 운용 가능하며, 둘 다 컴파일 시 바이트 코드를 생성합니다. 따라서 코틀린 코드는 자바에서 호출될 수 있고 그 반대도 가능합니다.
-
코틀린에서 변수를 선언하는 방법은 무엇인가요? 선언은 자바와 어떻게 다른가요?
자바와 코틀린 변수 선언 사이에는 두 가지 주요 차이점이 있습니다:
-
선언의 유형 자바에서 선언은 다음과 같습니다:
String s = "Java String"; int x = 10;
코틀린에서 선언은 다음과 같습니다:
val s: String = "Hi" var x = 5
코틀린에서는 선언이
val
또는var
로 시작하고 선택적으로 타입이 따릅니다. 코틀린은 타입 추론을 사용하여 타입을 자동으로 감지할 수 있습니다. -
기본 값 다음은 자바에서 가능합니다:
String s:
다음은 코틀린에서 유효하지 않은 변수 선언입니다.
val s: String
-
-
val과 var 선언의 차이는 무엇인가요? String을 Int로 어떻게 변환하나요?
val
변수는 변경할 수 없습니다. 그들은 자바의 final 수정자처럼 작동합니다.var
는 재할당할 수 있습니다. 재할당된 값은 동일한 데이터 유형이어야 합니다.fun main(args: Array<String>) { val s: String = "Hi" var x = 5 x = "6".toInt() }
우리는
toInt()
메서드를 사용하여 String을 Int로 변환합니다. -
코틀린의 Null 안전성과 Nullable 타입은 무엇인가요? Elvis 연산자는 무엇인가요?
코틀린은 널 안전성에 많은 중요성을 부여합니다. 이는 널 포인터 예외를 방지하기 위한 접근 방식으로,
String?
,Int?
,Float?
등과 같은 nullable 타입을 사용합니다. 이들은 래퍼 타입으로 작동하며 널 값을 보유할 수 있습니다. Nullable 값은 다른 nullable 또는 기본 유형의 값에 추가할 수 없습니다. 기본 유형을 검색하려면 Nullable 타입을 언래핑하는 안전한 호출을 사용해야 합니다. 언래핑할 때 값이 널이면 무시하거나 대신 기본 값을 사용할 수 있습니다. Elvis 연산자는 Nullable에서 값을 안전하게 언래핑하는 데 사용됩니다. 이는 널 가능성이 있는 유형 위에?:
로 표시됩니다. 오른쪽의 값은 널을 보유하는 경우에 사용됩니다.var str: String? = "JournalDev.com" var newStr = str?: "Default Value" str = null newStr = str?: "Default Value"
-
무엇이
const
인가요? 그것은val
과 어떻게 다른가요?기본적으로
val
속성은 런타임에 설정됩니다.val
에 const 수정자를 추가하면 컴파일 타임 상수가 됩니다.const
는var
이나 그 자체에 사용할 수 없습니다.const
는 로컬 변수에 적용할 수 없습니다. -
코틀린은 int, float, double과 같은 기본 유형을 사용할 수 있게 합니까?
언어 수준에서는 위에서 언급한 유형을 사용할 수 없지만, 컴파일된 JVM 바이트 코드에는 확실히 있습니다.
-
모든 Kotlin 프로그램의 진입점은 무엇인가요?
main
함수는 모든 Kotlin 프로그램의 진입점입니다. Kotlin에서는 클래스 내부에 main 함수를 작성하지 않을 수 있습니다. JVM을 컴파일할 때 암시적으로 클래스에 캡슐화됩니다.Array<String>
형식으로 전달된 문자열은 명령줄 인수를 검색하는 데 사용됩니다. -
어떻게
!!
가 ?와 다른가요? null 값을 해체하는 데 있어 안전한 방법이 있나요?!!
은 nullable 타입을 강제로 해체하여 값을 가져오는 데 사용됩니다. 반환된 값이 null이면 런타임 충돌이 발생합니다. 따라서!!
연산자는 값이 절대로 null이 아님을 확신할 때만 사용해야 합니다. 그렇지 않으면 null 포인터 예외가 발생할 수 있습니다. 반면에, ?.은 안전한 호출을 수행하는 Elvis 연산자입니다. 아래와 같이 nullable 값을 안전하게 해체하기 위해 람다 표현식let
을 사용할 수 있습니다.여기서 let 표현식은 nullable 타입을 안전하게 해체합니다.
-
함수는 어떻게 선언되나요? Kotlin 함수가 왜 최상위 함수로 알려져 있나요?
fun sumOf(a: Int, b: Int): Int{ return a + b }
:
다음에 함수의 반환 유형이 정의됩니다. Kotlin에서 함수는 Kotlin 파일의 최상위에 선언될 수 있습니다. -
Kotlin에서 ==와 === 연산자의 차이점은 무엇인가요?
\== is used to compare the values are equal or not. === is used to check if the references are equal or not.
- public
- internal
- protected
- private
`public` is the default visibility modifier.
```
class A{
}
class B : A(){
}
```
**NO**. By default classes are final in Kotlin. To make them non-final, you need to add the `open` modifier.
```
open class A{
}
class B : A(){
}
```
Constructors in Kotlin are of two types: **Primary** - These are defined in the class headers. They cannot hold any logic. There's only one primary constructor per class. **Secondary** - They're defined in the class body. They must delegate to the primary constructor if it exists. They can hold logic. There can be more than one secondary constructors.
```
class User(name: String, isAdmin: Boolean){
constructor(name: String, isAdmin: Boolean, age: Int) :this(name, isAdmin)
{
this.age = age
}
}
```
`init` is the initialiser block in Kotlin. It's executed once the primary constructor is instantiated. If you invoke a secondary constructor, then it works after the primary one as it is composed in the chain.
String interpolation is used to evaluate string templates. We use the symbol $ to add variables inside a string.
```
val name = "Journaldev.com"
val desc = "$name now has Kotlin Interview Questions too. ${name.length}"
```
Using `{}` we can compute an expression too.
By default, the constructor arguments are `val` unless explicitly set to `var`.
**NO**. Unlike Java, in Kotlin, new isn't a keyword. We can instantiate a class in the following way:
```
class A
var a = A()
val new = A()
```
when is the equivalent of `switch` in `Kotlin`. The default statement in a when is represented using the else statement.
```
var num = 10
when (num) {
0..4 -> print("value is 0")
5 -> print("value is 5")
else -> {
print("value is in neither of the above.")
}
}
```
`when` statments have a default break statement in them.
In Java, to create a class that stores data, you need to set the variables, the getters and the setters, override the `toString()`, `hash()` and `copy()` functions. In Kotlin you just need to add the `data` keyword on the class and all of the above would automatically be created under the hood.
```
data class Book(var name: String, var authorName: String)
fun main(args: Array<String>) {
val book = Book("Kotlin Tutorials","Anupam")
}
```
Thus, data classes saves us with lot of code. It creates component functions such as `component1()`.. `componentN()` for each of the variables. [](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-data-classes.png)
Destructuring Declarations is a smart way to assign multiple values to variables from data stored in objects/arrays. [](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-destructuring-declarations.png) Within paratheses, we've set the variable declarations. Under the hood, destructuring declarations create component functions for each of the class variables.
[Inline functions](/community/tutorials/kotlin-inline-function-reified) are used to save us memory overhead by preventing object allocations for the anonymous functions/lambda expressions called. Instead, it provides that functions body to the function that calls it at runtime. This increases the bytecode size slightly but saves us a lot of memory. [](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-inline-functions.png) [infix functions](/community/tutorials/kotlin-functions) on the other are used to call functions without parentheses or brackets. Doing so, the code looks much more like a natural language. [](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2018/04/kotlin-interview-questions-infix-notations.png)
Both are used to delay the property initializations in Kotlin `lateinit` is a modifier used with var and is used to set the value to the var at a later point. `lazy` is a method or rather say lambda expression. It's set on a val only. The val would be created at runtime when it's required.
```
val x: Int by lazy { 10 }
lateinit var y: String
```
To use the singleton pattern for our class we must use the keyword `object`
```
object MySingletonClass
```
An `object` cannot have a constructor set. We can use the init block inside it though.
**NO**. Kotlin doesn't have the static keyword. To create static method in our class we use the `companion object`. Following is the Java code:
```
class A {
public static int returnMe() { return 5; }
}
```
The equivalent Kotlin code would look like this:
```
class A {
companion object {
fun a() : Int = 5
}
}
```
To invoke this we simply do: `A.a()`.
```
val arr = arrayOf(1, 2, 3);
```
The type is Array<Int>.
Kotlin 면접 질문과 답변은 여기까지입니다.
Source:
https://www.digitalocean.com/community/tutorials/kotlin-interview-questions