아래의 글은 드미트리 제메로프, 스베트라나 이사코바 저/오현석역,『Kotlin in Action』,에이콘출판사(2017)의 내용을 기반으로 작성하였습니다. 

 

널 가능성과 컬렉션

List<Int?> : 리스트 자체는 널이 아님, Int는 널일 수 있음. 

List<Int>? : 리스트 자체는 널일 수 있음. Int는 널 아님

List<Int?>? : 리스트 자체가 널일 수 있고, Int도 널 일수 있음

List<Int> :  리스트도 널 아니고, Int도 널 아님.

 

읽기 전용과 변경 가능한 컬렉션

kotlin.collections.Collection : 컬렉션에 연산 수행하지만 읽기 전용이고, 수정을 가 할 수 없음

kotlin.collections.MutableCollection: 컬렉션에 수정 (원소 추가, 삭제 등) 가능

 

코틀린 컬렉션 : 읽기전용, 변경 가능 

읽기전용 인터페이스 : Interable

변경가능 인터페이스 : MutableIterable

kotlin

 

Java

컬렉션 생성 함수 

type Read Only Mutable
List listOf mutableListOf, arrayListOf
Set setOf mutableSetOf, hashSetOf, 
linkedSetOf, sortedSetOf
Map mapOf mutableMapOf, hashMapOf,
linkedMapOf, sortedMapOf

 

java와 혼용할때 생기는 문제

kotlin에서는 listOf생성은 readonly라고 하였는데 변경되어 있음을 아래의 코드로 증명

// java code

public class CollectionUtils {
	public static List<String> uppercaseAll(List<String> items) {
    	for (int i = 0; i < items.size(); i++){
        	items.set(i, items.get(i).toUpperCase());
        }
    }
}


// kotlin code
fun printlnUppercase(list: List<String) {
	println(CollectionUtils.uppercaseAll(list)
    println(list.first())
}


>>> var list = listOf("a", "b", "c")
>>> printlnUppercase(list)
[A, B, C]
A


 

코틀린에서는 readonly와 mutable의 interface가 다르므로 메소드 signature에 클래스를 명시적으로 읽기전용인지 변경가능인지

명시해야되므로, 혼용이 되지 않음.

더 어려운 경우는 자바에서 메소드에 컬렉션이 signature 로 들어간 경우 kotlin에서 해당 메소드를 오버라이드 할 경우, 

이때는 읽기전용으로 override할지, 변경가능으로 override해야할지를 판단해야함. 이건 케바케

 

코틀린 배열

코틀린 배열은 타이 파라미터를 받는 클래스

fun main(args: Array<String>) {
	for (i in args.indies) {
    	println("$i = ${args[i]}")
    }
}

 

코틀린 배열 생성

arrayOf

arrayOfNulls : 모든 원소가 null이고 인자로 넘긴 크기로 된 배열

코틀린 배열에도 확장함수 : (filter, map 등 ) 사용 가능

 

>>> val letters = Array<String>(26) { i -> ('a'+i).toString() }
>>> println(letters.joinToString(""))
abc....xyz


>>> val strings = listOf("a", "b", "c")
>>> println("%s/%s/%s".format(*strings.toTypedArray()))
a/b/c

>>> val fiveZeros = IntArray(5)
>>> val fiveZerosToo = IntArrayOf(0, 0, 0, 0, 0)

>>> val squares = IntArray(5) { i -> (i+1) * (i+1) }
>>> println(squares.joinToString())
1, 4, 9, 16, 25

fun main(args: Array<String>) {
	args.forEachIndexed { index, element -> 
    	println("$index : $element" )
    }
}

 

references

medium.com/@anhristyan/kotlin-collections-inside-part-1-2ad270586f4a

 

Kotlin Collections inside. Part 1.

Everyday during Java/Android development we use collection for different purposes: modifying data collections, displaying an UI with a list…

medium.com

www.programmersought.com/article/1599105415/

 

Collection framework in Kotlin - Programmer Sought

Collection framework in Kotlin tags: kotlin  set  Extension function  List  Map blog address:http://sguotao.top/Kotlin-2018-10-19-Kotlin collection framework.html In order to be good at it, it must be a tool. In Java, the collection framework occu

www.programmersought.com

 

+ Recent posts