Kotlin

Kotlin 시작하기

팅리엔 2021. 5. 2. 22:52

const

  • 컴파일 타임에 결정됨
  • read-only
  • Top-level / object의 멤버 / companion object의 멤버
  • No custom getter

lateinit

- var, non-null 프로퍼티에 사용
- 초기화 되기 전에 접근시 예외 발생
if (foo::bar.isInitialized) {
	println(foo.bar)
}

data class

  • getters & setters in case of `var`
  • equals()
  • hashCode()
  • toString()
  • copy()
  • componentN()

read-only list

val list = listOf("a", "b", "c")

read-only map

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

iterate over a range

for (i in 1..100) { ... }  // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }

Extension functions

fun String.spaceToCamalCase() {...}

"Convert this to camalcase".spaceToCamelCase()

Singlton

object Resource {
    val name = "Name"
}

Instantiate an abstract class

abstract class MyAbstractClass {
    abstract fun doSomething()
    abstract fun sleep()
}

fun main() {
    val myObject = object : MyAbstractClass() {
        override fun doSomething() {
            // ...
        }

        override fun sleep() { // ...
        }
    }

    myObject.doSomething()
}

if-not-null

var files = File("test").listFiles()

println(files?.size)

if-not-null-else

var files = File("test").listFiles()

println(files?.size ?: "empty")

execute if not null

value?.let {
    ...
}

map if not null

val mapped = value?.let { transformValue(it) } ?: defaultValue

Call multiple methods on an object instance (with)

val myTurtle = Turtle()
with (myTurtle) {
    penDown()
    for (i in 1..4) {
        forward(100.0)
        turn(90.0)
    }
    penUp()
}

configure properties of an object (apply)

val myRantangle = Rantangle().apply {
    length = 4
    breadth = 5
    color = 0xFAFAFA
}

generic function that requires the generic type information

//  public final class Gson {
//     ...
//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
//     ...

inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)

swap two variables

var a = 1
var b = 2
a = b.also { b = a }

Coding Conventions

the contents of class order

  1. property declarations and initializer blocks
  2. secondary constructors
  3. method declarations
  4. companion object

modifiers order

public / protected / private / internal
expect / actual
final / open / abstract / sealed / const
external
override
lateinit
tailrec
vararg
suspend
inner
enum / annotation / fun
inline
infix
operator
data

wrap chained calls

val anchor = owner
    ?.firstChild!!
    .siblings(forward = true)
    .dropWhile { it is PsiComment || it is PsiWhiteSpace }

if vs when

Prefer using when if there are three or more options.

functions vs properties

In some cases functions with no arguments might be interchangeable with read-only properties.
Prefer a property over a function when the underlying algorithm:

  • does not throw
  • is cheap to calculate (or cached on the first run)
  • returns the same result over invocations if the object state hasn't changed

extension functions

Use extension functions liberally. Every time you have a function that works primarily on an object, consider making it an extension function accepting that object as a receiver. To minimize API pollution, restrict the visibility of extension functions as much as it makes sense. As necessary, use local extension functions, member extension functions, or top-level extension functions with private visibility.

Infix functions

Declare a function as infix only when it works on two objects which play a similar role. Good examples: and, to, zip. Bad example: add.
Do not declare a method as infix if it mutates the receiver object.

factory functions

class Point(val x: Double, val y: Double) {
    companion object {
        fun fromPolar(angle: Double, radius: Double) = Point(...)
    }
}

scope functions

Kotlin provides a set of functions to execute a block of code in the context of a given object: let, run, with, apply, and also. For the guidance on choosing the right scope function for your case, refer to Scope Functions.

 

scope function을 사용하지 않으면?

- 그 object를 참조하는 변수가 있어야 하고

- 그 변수를 반복적으로 사용해야 한다

'Kotlin' 카테고리의 다른 글

Kotlin 문법 - 표준 라이브러리편  (0) 2022.10.08
Kotlin 문법 - 중수편  (1) 2022.10.03
Kotlin 문법 - 초보편  (0) 2022.09.29
Kotlin 문법 - 입문편  (0) 2022.09.28
TypeScript 시작하기  (0) 2021.09.08