phantasmicmeans 기술 블로그

1. Kotlin - Variables, Functions 본문

Programming/Kotlin

1. Kotlin - Variables, Functions

phantasmicmeans 2021. 1. 22. 12:47

Hello World

intellj에 코틀린 프로젝트 생성 및 Hello world는 아래 문서로

1. Variables

Kotlin은 불변성을 강제하지 않는다. var / val을 사용하여 이를 컨트롤 하면 된다.

  • val: immutable
  • var: mutable
val a: String = "initial" // immutable  
var b: Int = 1  // mutable 

또한 Kotlin은 타입 추론을 잘한다. 변수 선언시 타입을 포함하지 않아도 대입 값을 보고 타입 추론한다.

var c = 3 // compiler infers the type Int 
var d = "ABC" // compiler infers the type String 

Kotlin 지원 타입은 여기서

 

2. Functions

  • kotiln은 Unit이라는 void 타입을 가지고 이는 생략 가능하다.
fun printMeessage(message: String) : Unit {
    println(message)
}

fun printMeessage(message: String) {
    println(message)
}
  • function은 optional parameter를 가질 수 있다.
fun printMessageWithPrefix(message: String, prefix: String = "Info") {
    println("[$prefix] $message")
}

fun main() {
    printMessageWithPrefix("Hello") // message 
    printMessageWithPrefix(message = "Hello", prefix = "Log") // message, prefix both 
}

Single Expression Function

  • single expression function 은 리턴값을 가져야한다.
// single expression function 
fun multiply(x: Int, y: Int) = x * y

// normal function 
fun multiply(x: Int, y: Int) {
    return x * y
}

Infix Function

Kotlin은 Infix notation을 통해 닷 연산자나 대괄호를 사용하지 않고 특정 function을 호출할 수 있다. 이러한 function을 Infix function 라 부르며 조금 더 자연어에 가까운 가독성을 가질 수 있다.

infix notation(중위 표기법)

  • "2 + 2" 에서의 더하기 기호와 같이 피연산자 사이에 연산자가 존재한다.

Kotlin에서 Map 을 정의할 때 아래와 같은 형태로 자주 보게 되는데, 이는 kotlin-stdlib에 정의된 infix function인 to()를 활용한다.

var map:Map<Int, String> = mapOf(
     1 to "one",
     2 to "one",
     3 to "one"
)

kotlin-stdlib에 정의된 to()는 infix funtion으로 Pair<A, B> 를 반환한다.

public data class Pair<out A, out B>(
    public val first: A,
    public val second: B
) : Serializable {

... 생략 ... 

/**
 * Creates a tuple of type [Pair] from this and [that].
 *
 * This can be useful for creating [Map] literals with less noise, for example:
 * @sample samples.collections.Maps.Instantiation.mapFromPairs
 */
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)

이 외에도 다양한 Infix function이 존재하며 아래는 몇가지 예시들이다.

  • Boolean class에 정의된 and(), or(), xor()
var isBlocked = true
var isEnabled = false
if (isBlocked and isEnabled) { /* do something */}
if (isBlocked or isEnabled) { /* do something */ }  
  • String class에 정의된 matches(), zip()
    var str1 = "Hello world" matches "^Hello".toRegex()
    var str2 = "a" zip "b"

Custom Infix Function

아래처럼 custom하게 infix function을 정의할 수 있다.

class Person(val name: String) {
    var likedPeople = mutableListOf<Person>()
    infix fun likes(other: Person) {
        likedPeople.add(other)
    }
}

fun main() {
    var sophia = Person("Sophia")
    var claudia = Person("Claudia")
    sophia likes claudia   // infix notation also works on members functions
}

Infix As Extension

또 하나의 Infix function의 큰 장점은 기존 class의 extension method로도 활용될 수 있다는 점이다.

Java의 경우 라이브러리 혹은 기존 정의된 클래스에 function을 추가할 때 주로 상속 혹은 컴포지션을 통해 이를 행하기에 조금 까다롭다고 볼 수 있다

Kotlin은 Extension Functions을 통해 기존 클래스에 간단하게 function을 추가 및 확장 정의하여 사용할 수 있다.

실제로는 클래스를 수정하는 것이 아니라 static final로 메소드가 생성되는데.. extension function에 대한 내용은 차후에 조금 더 깊게 다룰 예정이니 이정도만 알고 넘어가도 될 듯 하다.

fun main() {
    infix fun Int.times(str: String) = str.repeat(this)
    println(2 times "Bye ") // calls the infix function

    // own implementation of 'to' creatively called 'onto'
    infix fun String.onto(other: String) = Pair(this, other) 
    var myPair = "McLaren" onto "Lucas" // calls the infix function
}

'Programming > Kotlin' 카테고리의 다른 글

6. Kotlin - Class Inheritance  (0) 2021.01.22
5. Kotlin - Class  (0) 2021.01.22
4. Kotlin - Return and Jumps  (0) 2021.01.22
3. Kotlin - Control-Flow  (0) 2021.01.22
2. Kotlin - Null Safety  (0) 2021.01.22
Comments