Kotlin 기초

Soomin Kim·2023년 1월 25일

Android

목록 보기
1/14

변수

var
overwrite O(중복 기재될 수 있음). 즉, 덮어쓸 수 있음.

var myName = "Soomin"
myName = "Other Name"

val
overwrite X, immutable

val MyName = "Soomin"
myName = "Other Name" // 에러

주석

// 
// TODO: Add function
/*
Multi line
Comment
*/
//type string
val myName = "Frank"
//type int 32 bit
var myage = 25

숫자 데이터 유형
//Integer Types: Byte(* bit), Short (16 bit)
// Int (32 bit), Long (64 bit)
// 숫자는 보통 int로 인식하기 때문에, Byte나 Short는 따로 지정을 해줘야 되고,
Long은 _로 구분하고, 가독성도 up
val myByte: Byte = 13
val myShort: Short = 125
val myInt: Int = 123123123
val myLong: Long = 39_123_235_135_325_235

// Floating Point number Types: Float (32 bit), Double (64 bit)
val myFloat: Float = 13.37F //F를 안붙이면 Double로 인식
val myDouble: Double = 3.141592395354534234

Type Inference
타입을 지정하지 않아도 value 값으로 type 결정

Bool, char, string type

var isSunny: Boolean = true

// Characters
val letterChar = 'A'
val digitChar = '1' 

//type string
val myStr = "Hello World"
var firstCharInStr = myStr[0] // 'H'
var lastCharInStr = myStr[myStr.length - 1] //'d'

String Interpolation

val myStr = "Hello World"
var firstCharInStr = myStr[0]
var lastCharInStr = myStr[myStr.length - 1]

print("First character $firstCharInStr and the length of myStr is ${myStr.length}")

연산자

산술 연산자: +, -, *, /, %

//Arithmetic operators (+, -, *, /, %)
    var result = 5+3 //8
    val a = 5
    val b = 3
    result = a / b // 1
    var resultDouble :Double
    val aa = 5.0
    val bb = 3
    resultDouble = aa / bb // 할당되는 result변수가 정수면, 정수값으로 들어감.
    print(resultDouble) // 1.66666
    // % : 나머지 값
    result = 15%4 // 3

비교 연산자: ==, !=, <, >, <=, >=


    // Comparison operators (==, !=, <, >, <=, >=)
    val isEqual = 5 == 3
    println("isEqual is $isEqual") // false

    val isNotEqual = 5 != 5
    // Kotlin has a feature called String Interpolation.
    // This feature allows you to directly insert a template expression inside a String.
    // Template expressions are tiny pieces of code that are evaluated and
    // their results are concatenated with the original String.
    // A template expression is prefixed with $ symbol.
    // Following are examples of String interpolation
    // String interpolation
    println("isNotEqual is $isNotEqual") // false
    println("is5greater3 ${5>3}") // true
    println("is-5less3 ${-5<3}") // true
    println("is5LowerEqual3 ${5 <= 3}") // false
    println("is5GreaterEqual5 ${5 >= 5}") // true

증감 연산자: +=, -=, *=, /=, %=

    // Assignment operators (+=, -=, *=, /=, %=)
    var myNum = 5
    myNum += 3
    println("myNum is $myNum") // 8
    myNum *= 4
    println("myNum is $myNum") // 32

    //Increment & Decrement operators (++, -=)
    myNum++
    println("myNum is ${myNum}") // 33
    // Increments after use
    println("myNum is ${myNum++}") // 33
    // Increments before use
    println("myNum is ${++myNum}") // 35
    println("myNum is ${--myNum}") // 34

If, When

// 흐름 제어 Control Flow
    var heightPerson1 = 170
    var heightPerson2 = 189
    if (heightPerson1 > heightPerson2) {
        print("Use raw force")
    }else if (heightPerson1 == heightPerson2) {
        println("Use your power technique 1332")
    }else{
        println("Use technical skill")
    }
    val myage = 31

    if (myage >=30)
        println("you're over 30")

    if ( myage >= 21) {
        println("You may drink in US")
    } else if ( myage >= 18){
        println("you may vote")
    } else if (myage >= 16){
        println("you may drive")
    } else{
        print("you are too young")
    }

    // String in if
    var name = "Soomin"
    if (name == "Soomin"){
        println("Welcome home Soomin")
    }else{
        print("who are you?")
    }
    val isRainy = true
    if(isRainy)
        println("It's rainy")


    // When 조건식
    var season = 3
    when(season){
        1 -> println("Spring")
        2 -> println("Summer")
        3 -> {
            println("Autumn")
            println("Fall")
        }
        4 -> println("Winter")
        else -> println("Invalid Season")
    }

    var month = 3
    when(month) {
        in 3..5 -> println("spring") // 3~5
        in 6..8 -> println("summer") // 6~8
        in 7..9 -> println("Fall") // 7~9
        12, 1, 2 -> println("Winter") // 12,1,2
        else -> println("Invalid season")
        // 내려가는: 12 downTo 2
    }

    var mymyage = 20
    when(mymyage) {
        !in 0..20 -> println("now you may drink in the US")
        // in 21..150-> println("now you may drink in the US")
        in 18..20 -> println("you may vote now")
        16,17 -> println("you may drive now")
        else -> println("you are too young")
    }

    // When에서 is 사용
    var x : Any = 13.37
    when(x) {
        is Int -> print("$x is Int")
        is Double -> println("$x is a Double")
        !is Double -> println("$x is not a Double")
        is String -> println("$x is a String")
        else -> println("$x is none of the above")
    }
    
    //더 깔끔한 ver.
    val x : Any = 13.37
	//assign when to a variable
  	val result =  when(x) {
	//let condition for each block be only a string
        is Int -> "is an Int"
        !is Double -> "is not Double"
        is String -> "is a String"
        else -> "is none of the above"
    }
	//then print x with the result
	print("$x $result")

While, for

var condition = true
    // Loops
    // While Loop
    // While loop executes a block of code repeatedly as long as a given condition is true
    while(condition) {
        // code to be executed
    }
 
    var y = 1
    while(y <= 10) {
        println("$y ")
        y++
    }
 
    // Do while loop
    // The do-while loop is similar to while loop except that it 
    // tests the condition at the end of the loop. 
    // This means that it will at least execute the body once
    var z = 1
    // do~while은 조건에 상관없이 한번은 꼭 실행
    // ex. 프린트 연결 여부에 상관없이 처음에 목록 한번 가져오고, 연결되어있으면 프린트 하기
    do {
        print("$z ")
        z++
    } while(z <= 10)
 
    var feltTemp = "cold"
    var roomTemp = 10
    while (feltTemp == "cold"){
        roomTemp++
        if(roomTemp == 20){
            feltTemp = "comfy"
            println("it's comfy now")
        }
    }
 
 
    // For Loop
    // A for-loop is used to iterate through ranges, arrays, collections, or anything 
    // that provides an iterator (You’ll learn about iterator, arrays, ranges and collections in a future lectur    e).
    for(num in 1..10) {
        print("$num ")
    }
 
    // infix notation
    for(i in 1 until 10) { // Same as - for(i in 1.until(10))
        print("$i ")
    }
 
    for(i in 10 downTo 1) {     // Same as - for(i in 10.downTo(1))
        print("$i ")
    }
 
    for(i in 1 until 10 step 2) { // Same as - for(i in 1.until(10).step(2))
        print("$i ")
    }

break, continue

// break, continue
    for (i in 1 until 20){
        if (i/2==5){
            break
            print("$i ") // 1 2 3 4 5 6 7 8 9 10
        }
    }
    
    for (i in 1 until 20){
        if (i/2==5){
            continue
            print("$i ") // 1 2 3 4 5 6 7 8 9 12 13..
        }
    }

함수

fun main(){
    // argument
    var result = addUp(2, 3)
    print("Result is $result")

    var averageNum = average(4.0, 9.0)
    print("Result is $averageNum")
}

fun myFunction() {
    print("Called from myFunction")
}

// Method - Function within a class
// Parameter (input)
fun addUp(a: Int, b: Int) : Int {
    //output
    return a + b
}

fun average(a: Double, b: Double) : Double{
    return (a + b) / 2
}

// Article on Kotlin words https://blog.kotlin-academy.com/kotlin-programmer-dictionary-function-vs-method-vs-procedure-c0216642ee87

Nullable, Elvis, Non-Nullable

// NULLABLES/OPTIONALS in Kotlin
// Kotlin supports nullability as part of its type System.
// That means You have the ability to declare whether 
// a variable can hold a null value or not.
// By supporting nullability in the type system,
// the compiler can detect 
// possible NullPointerException errors at compile time 
// and reduce the possibility of having them thrown at runtime.
	var name: String = "Soomin"
    name = "Sophie"
    // name = null : error. Nullable 아닌 STring 변수는 Null이 될 수 없음.
    var nullableName: String? = "Soomin"
    //nullableName = null

    var len = name.length
    // but the same methods won't work on nullable types
    val len2 = nullableName.length // Compilation Error
    val upper2 = nullableName.toLowerCase()  // Compilation Error
    // So how can we solve this? We could do a null check before hand
    // kotlin 방식
    var len2 = nullableName?.length
    // 구식
    val nullableName2: String? = "Denis"
 
    if(nullableName2 != null) {
        println("Hello, ${nullableName2.toLowerCase()}.")
        println("Your name is ${nullableName2.length} characters long.")
    } else {
        println("Hello, Guest")
    }
	// This works but seems to be quite some work...
// So how about we shorten the syntax...
// Kotlin provides a Safe call operator, ?.  
// It allows you to combine a null-check and 
// a method call in a single expression.
 
    nullableName2?.toLowerCase()
 
// You can use methods on a nullable variable like this
    val nullableName3: String? = null
 
    println(nullableName3?.toLowerCase()) // prints null
    println(nullableName3?.length) // prints null
 
// You can perform a chain safe calls:
    //val wifesAge: String? = user?.wife?.age
 
 
// Let'S say we don’t want to print anything if 
// the variable is null?
 
// In order to perform an operation only if the 
// variable is not null, we can use the safe call 
// operator with let -
 //Nullable변수?.let{null이 아닌 경우에만 실행할}
 
    val nullableName4: String? = null
 
    nullableName4?.let { println(it.toLowerCase()) }
    nullableName4?.let { println(it.length) }
// Prints nothing because there nullableName is null 
// and we used let to prevent anything from being performed
 
 
// What if we would like to enter a default value?
// Then we can use the elvis operator ?:
    val name2 = nullableName4 ?: "Guest"
    
    //val wifesAge2: String? = user?.wife?.age ?: 0
 
 
// Not null assertion : !! Operator
// The !! operator converts a nullable type to a 
// non-null type, and throws a NullPointerException 
// if the nullable type holds a null value.
// This is risky, and you should only use it if 
// you are 100% certain, that there will be a value in 
// the variable.
    val nullableName5: String? = null
    nullableName5!!.toLowerCase() // Results in NullPointerException
 
}

// ?: Elvis operator
    //null이면, Guest 할당
   val name = nullableName ?: "Guest"
    println("name is $name")

    // nulldlaus dpfj
    nullableName!!.toLowerCase()

    // safe call operator in chain
    val wifesAge: String? = user?.wife?.age ?: 0

 
profile
개발자지망생

0개의 댓글