본문 바로가기

Android/Kotlin

기본 fun 만들기

반응형

안녕하세요. 오늘은 kotlin에서 fun들을 만들어 테스트 해보던 "기본"에 대해 올려볼까 합니다.


항상 "기초"가 중요하니까요!


fun onlyReadMethod() { val list = listOf("a", "b", "c") // 읽기 전용 리스트 val map = mapOf("a" to 1, "b" to 2, "c" to 3) // 읽기 전용 맵 } fun sum(a: Int, b: Int) = a + b        // { return a+b } 와 같은 내용 fun comparison(a: Int, b: Int) = if (a > b) a else b /* fun comparison(a:Int, b:Int): Int { return if(a>b) a else b } */ fun getStringLength(obj: Any): Int? {        // ? << null 처리 if (obj is String) return obj.length // 'obj' is automatically cast to 'String' int this branch else if (obj !is String) return null return null } fun listTest() { val arrayList = ArrayList<String>() for (s in arrayList) { println("string : $s") } } fun filterTest() { val list1 = listOf(1, 3, 5, 7, 9) list1.filter { it > 5 }.map { println("index " + (it * 2)) } // 코틀린 null 처리 val list2: List<Int?> = listOf(1, 2, null, 3, 4, 5) val intList: List<Int> = list2.filterNotNull() intList.map { println("NotNull it $it") } } fun printProduct(arg1: String, arg2: String) { val x = Integer.parseInt(arg1) val y = Integer.parseInt(arg2) // Using `x * y` yields error because they may hold nulls. if (x != null && y != null) { // x and y are automatically cast to non-nullable after null check println(x * y) } else { println("either '$arg1' or '$arg2' is not a number") } } fun getListOf() { val items = listOf("apple", "banana", "kiwifruit") for (item in items) { println(item) } println("---------------------------------------") for (index in items.indices) { println("item at $index is ${items[index]}") } } fun getWhile() { val items = listOf("apple", "banana", "kiwifruit") var index = 0 while (index < items.size) { println("item at $index is ${items[index]}") index++ } } fun getWhen() { cases("Hello") // String cases(1) // Int cases(System.currentTimeMillis()) // Long cases("hello") // Unknown } fun cases(obj: Any) { // 인스턴스 체크 when (obj) { 1 -> println("One") "Hello" -> println("Greeting") is Long -> println("Long") !is String -> println("Not a string") else -> println("Unknown") } } fun getRanges() { val x = 10 val y = 9 if (x in 1..y + 1) { println("fits in range") } println("---------------------------------------") for (z in 1..10) { // 10 포함 print("$z, ") } println("---------------------------------------") for (z in 1 until 10) { // 10 포함 x print("$z, ") } println("---------------------------------------") val list = listOf("a", "b", "c") if (-1 !in 0..list.lastIndex) { println("-1 is out of range") } println("list.lastIndex : ${list.lastIndex}") println("list.size : ${list.size}") println("list.indices : ${list.indices}") // 범위를 나타내는 것 "0..list.lastIndex" 와 같은 결과를 나타냄 if (list.size !in list.indices) { println("list size is out of valid list indices range too") } println("---------------------------------------") for (x in 1..10 step 2) { print("$x, ") } println() for (x in 9 downTo 1) { print("$x, ") } println() for (x in 9 downTo 0 step 3) { print("$x, ") } }


이런식으로 가장 기본에 대한 문법들과 변수 선언 등에 대해 공부했습니다.


아무리 테스트한 결과가 올라온 싸이트가 많더라도, 자기가 직접 해보고 결과를 눈에 확인해봐야지 이런식으로 쓰이는 구나를


알 수 있으니까요!


또 코틀린에서는 DTO를 만들때 getter / setter 을 굳이 선언해주지 않아도 됩니다.


/*
DTO 작성(POJO / POCO)
기본 제공하는 기능
    모든 프로퍼티의 getter(var 의 경우 setter 포함)
    equals()
    hasCode()
    toString()
    copy()
    component1(), component2() ....
 */

data class SampleVal(val name:String, val email:String) // val 는 불변이므로 읽기 전용이며, 컴파일러가 getter 만 생성


val 로 선언시에는 수정이 불가능하므로 처음 선언한

val sampleVal: SampleVal = SampleVal("Name", "c@c.com")
            println("sampleVal.name : "+sampleVal.name)
            println("sampleVal.email : "+sampleVal.email)
            println("-----------------------------------------------")

이런 식으로밖에 가져오지 못합니다.


하지만, var로 선언한

data class SampleVar(var name:String, var email:String)
// var는 읽고 쓰기가 가능하므로, 컴파일러가 gettet/setter 자동으로 생성

이 class는 변수를 수정이 가능하고 읽고 쓰기가 가능하므로, 

val sampleVar: SampleVar = SampleVar("Name", "c@c.com")
            println("SampleVar.name : "+sampleVar.name)
            println("SampleVar.email : "+sampleVar.email)
            sampleVar.name = "Change"
            sampleVar.email = "e@e.com"
            println("SampleVar.name : "+sampleVar.name)
            println("SampleVar.email : "+sampleVar.email)
            println("-----------------------------------------------")

이렇게 초기값인 Name을 Change로, c@c.com 을 e@e.com 으로 변경시킬 수 있습니다.


-------------------------이상 간단한 kotlin 사용법에 대해 알아보았습니다.




반응형