// 한번만 할당가능한(읽기전용) 지역변수 정의 funmain(args:Array<String>){ vala:Int=1// immediate assignment valb=2// `Int` type is inferred valc:Int// Type required when no initializer is provided c=3// deferred assignment println("a = $a, b = $b, c = $c") } -------------------------------------------------------- a=1,b=2,c=3
지역변수 정의 2
1 2 3 4 5 6 7 8
// 여러번 할당가능한 변수 정의 funmain(args:Array<String>){ varx=5// `Int` type is inferred x+=1 println("x = $x") } -------------------------------------------------------- x=6
주석
1 2 3 4 5 6
// 한줄 주석 // This is an end-of-line comment
// 블럭 주석(Java와 달리 Kotlin의 블록 주석은 중첩 될 수 있습니다.) /* This is a block comment on multiple lines. */
string 템플릿
1 2 3 4 5 6 7 8 9 10 11 12
funmain(args:Array<String>){ vara=1 // simple name in template: vals1="a is $a"
a=2 // arbitrary expression in template: vals2="${s1.replace("is", "was")}, but now is $a" println(s2) } -------------------------------------------------------- awas1,butnowis2
// A reference must be explicitly marked as nullable when null value is possible. // Return null if str does not hold an integer: funparseInt(str:String):Int?{ returnstr.toIntOrNull() }
// 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") } }
// The is operator checks if an expression is an instance of a type. If an immutable local variable or property is checked for a specific type, there's no need to cast it explicitly fungetStringLength(obj:Any):Int?{ if(objisString){ // `obj` is automatically cast to `String` in this branch returnobj.length }
// `obj` is still of type `Any` outside of the type-checked branch returnnull }
fungetStringLength(obj:Any):Int?{ // `obj` is automatically cast to `String` on the right-hand side of `&&` if(objisString&&obj.length>0){ returnobj.length }
fundescribe(obj:Any):String= when(obj){ 1->"One" "Hello"->"Greeting" isLong->"Long" !isString->"Not a string" else->"Unknown" }
funmain(args:Array<String>){ println(describe(1)) println(describe("Hello")) println(describe(1000L)) println(describe(2)) println(describe("other")) } -------------------------------------------------------- One Greeting Long Notastring Unknown
Using ranges 1
1 2 3 4 5 6 7 8 9 10
// in 연산자를 사용하여 숫자가 범위 내에 있는지 확인 funmain(args:Array<String>){ valx=10 valy=9 if(xin1..y+1){ println("fits in range") } } -------------------------------------------------------- fitsinrange
Using ranges 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// in 연산자를 사용하여 숫자가 범위 내에 있는지 확인 funmain(args:Array<String>){ vallist=listOf("a","b","c")
if(-1!in0..list.lastIndex){ println("-1 is out of range") } if(list.size!inlist.indices){ println("list size is out of valid list indices range too") } } -------------------------------------------------------- -1isoutofrange listsizeisoutofvalidlistindicesrangetoo
// or over a progression funmain(args:Array<String>){ for(xin1..10step2){ print(x) } for(xin9downTo0step3){ print(x) } } -------------------------------------------------------- 135799630
// in 연산자를 사용하여 컬렉션에 개체가 포함되어 있는지 확인 funmain(args:Array<String>){ valitems=setOf("apple","banana","kiwi") when{ "orange"initems->println("juicy") "apple"initems->println("apple is fine too") } } -------------------------------------------------------- appleisfinetoo
코틀린 컬렉션 3
1 2 3 4 5 6 7 8 9 10 11 12
// 람다 식을 사용하여 콜렉션 필터링 및 매핑 funmain(args:Array<String>){ valfruits=listOf("banana","avocado","apple","kiwi") fruits .filter{it.startsWith("a")} .sortedBy{it} .map{it.toUpperCase()} .forEach{println(it)} } -------------------------------------------------------- APPLE AVOCADO