일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 탐색
- Java
- BFS
- unittest
- spring cloud netflix zuul
- unit
- spring cloud
- Dynamic Routing
- netflix
- forkandjoinpool #threadpool #jvm #async #non-blocking
- springcloud
- dfs
- container image #docker #layer #filesystem #content addressable
- docker
- Eureka
- java #jvm #reference #gc #strong reference
- microservice architecture
- 단위테스트
- test
- netflix eureka
- Spring Data Redis
- spring cloud netflix eureka
- zuul
- code refactoring
- api-gateway
- reactive
- 서비스스펙
- spring cloud netflix
- 설계
- Today
- Total
phantasmicmeans 기술 블로그
1. Kotlin - Variables, Functions 본문
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 |