Lesson1 : Kotlin Basics

Yunny.Log ·2022년 9월 17일
0
post-thumbnail

Kotlin Course - Tutorial for Beginners

var val

  • val : 한번 지정되면 변경, 수정 안됨 immutable
  • var : 재지정 가능 mutable
    var width: Int = 12
var/val 변수이름 : 타입 = 값

  • 함수 벗어나서 변수 선언 가능
val name: String = "mayo"
var greeting: String = "hello"

fun main(args: Array<String>) {
    println("Hello World!")

    fun PrintHello(){
        print("hello my first kotlin ~ ")
        print(name)
        print(greeting)
    }

    PrintHello()
}

string 다루기,

  • 문자열 안에 "$"+변수명 쓰면 변수가 문자열에 잘 나타나
val numberOfDogs = 3
val numberOfCats = 2

fun main(args: Array<String>) {
    println("Hello World!")
    println("Program arguments: ${args.joinToString()}")
    fun PrintHello(){
        print("I have $numberOfDogs dogs" + " and $numberOfCats cats")
    }
    PrintHello()
}

조건문 ,, 간편하다

    if(numberOfCats>numberOfDogs){
        print("\ncat saves the world")
    }else{
        print("\ndog saves the world")
    }

범위는 시작범위..끝범위 일케 표시,

  • 이때 시작범위<=~~<=끝범위 가 포함범위임
        for(i in 1..10){
         print(i)
     }

배열 선언하기

    val pets = arrayOf("cat", "catt", "cattt")
    for(i in pets){
        print(i)
    }

배열 안 인덱스, 값 출력

  • <배열 인덱스> - indices
  for ( index in pets.indices) {
      println("Item at $index is $pets[i]\n")
  }
  • <인덱스, 값 출력>
    for(i in pets.withIndex()){
        print("\n"+i)
    }

repeat


repeat(2) {
     print("Hello!")
}

for range - downTo, step

when

  • 약간 switch case 문 비슷
when (numberOfFish) {
    0  -> println("Empty tank")
    in 1..39 -> println("Got fish!")
    else -> println("That's a lot of fish!")
}

list (mutable, immutable)

  val instruments = listOf("trumpet", "piano", "violin")
  println(instruments)
  val instruments = mutableListOf("trumpet", "piano", "violin")
  println(instruments)
  • 헷갈 포인트 : With a list defined with val, you can't change which list the variable refers to, but you can still change the contents of the list!
  • 으음~ val이 가리키는 리스트는 변경 x 지만 리스트 내부 아이들은 건드리기 가능
  • Primitive type arrys : ByteArray , ShortArray, IntArray => 얘네들은 하나의 타입만 담기 가능,

arrayOf()

  • An array can contain different types!

Null safety!

  • variables cannot be null by default!
    : 코틀린에서 변수들은 기본으로 null이 될 수 없음
var numberOfBooks: Int = null

=> 에러 나지

Safe call operator " ? "

  • null 허용하려면 이렇게 해, 타입 뒤에? 붙여
var numberOfBooks: Int? = null

=> 에러 나지

The !! operator (null 이 아님을 쐐기박기)

  • use !! to force the variable into a non-null type. Then you can call methods/properties on it.
  • 이걸로 해놓으면 변수에 null 들어오면 nullException 나지
val len = s!!.length
  • Warning: Because !! will throw an exception, it should only be used when it would be exceptional to hold a null value.

Elvis 연산자

설명 출처

  • 엘비스 연산자는 ?:로 표현하며, ?:의 왼쪽 객체가 non-null이면 그 객체의 값이 리턴되고, null이라면 ?:의 오른쪽 값을 리턴

?.는 Safe call

설명 출처

  • ?.는 Safe call이라고 부르는 것인데, str?.length는 str 객체가 null일 때 null을 리턴하고, null이 아닐 때는 str.length를 리턴
fun main(args: Array<String>){

    val str: String? = "1234"
    val nullStr: String? = null

    var len: Int = str?.length ?: -1
    println("str.length: $len")

    len = nullStr?.length ?: -1
    println("nullStr.length: $len")

}

느낀점

  • 간단하다 편하다 왜 코틀린코틀린하는지 알겠다.
  • 멋쟁이 언어
  • 엘비스 연산자가 압도적으로 기억에 남는다. ?:

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJ8Z6yzVpuw3t-fm3nYeH25cMH47piNbl4csWJqVeMnUVMjsUb51mszww8K6MXyCdo3lU&usqp=CAU

reference

https://docs.google.com/presentation/u/0/

0개의 댓글

관련 채용 정보