kotlin
  • Kotlin
  • Variable
  • Function
  • First Class Citizen
  • High Order Function
  • Pure Function
  • Call by Value, Call by Name
  • Null Safe
  • Generic
  • Expression
    • if - else
    • when
    • try - catch
    • while
    • for
  • Class
    • abstract
    • constructor
    • Data Class
    • Default Value
    • enum
    • inheritance
    • interface
    • open
    • property
    • sealed
  • Kotlin Standard
    • let
    • with
    • apply
    • run
    • also
    • takeIf
    • takeUnless
    • use
    • repeat
  • Collections
    • Mutable
    • Immutable
    • Collections
    • Aggregate operations
      • any
      • all
      • count
      • fold
      • foldRight
      • fold vs foldRight
      • forEach
      • forEachIndexed
      • max
      • maxBy
      • min
      • minBy
      • none
      • reduce
      • reduceRight
      • sum
      • sumBy
    • Filtering operations
      • drop
      • dropLast
      • dropWhile
      • dropLastWhile
      • filter
      • filterNot
      • slice
      • take
      • takeLast
      • takeWhile
    • Mapping operations
      • map
      • mapIndexed
      • flatMap
      • groupBy
    • Elements operations
      • contains
      • elementAt
      • elementAtOrElse
      • elementAtOrNull
      • first
      • firstOrNull
      • indexOf
      • indexOfFirst
      • indexOfLast
      • last
      • lastIndexOf
      • lastOrNull
      • single
      • singleOrNull
    • Generation operations
      • partition
      • plus
      • minus
      • zip
      • unzip
    • Ordering operations
      • reversed
      • sorted
      • sortedBy
      • sortedDescending
      • sortedByDescending
Powered by GitBook
On this page
  1. Kotlin Standard

use

자바의 AutoCloseable 을 코틀린으로 구현해 놓은 것. 자바와 마찬가지로 AutoCloseable 이 가능하려면 Closeable 인터페이스를 상속받고 있어야만 한다.

// Java 1.6
Properties property = new Properties();
FileInputStream stream = new FileInputStream("config.properties");

try {
    property.load(stream);
} catch(Exception e) {
    stream.close();
}

// Java 1.7
Properties property = new Properties();
try (FileInputStream stream = new FileInputStream("config.properties")) {
    property.load(stream);
} // FileInputStream은 자동으로 close 된다.

public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var closed = false
    try {
        return block(this)
    } catch (e: Exception) {
        closed = true
        try {
            this?.close()
        } catch (closeException: Exception) {
            ;
        }
        throw e
    } finally {
        if (!closed) {
            this?.close()
        }
    }
}

val property = Properties()
FileInputStream("config.properties").use {
    property.load(it)
} // FileInputStream 이 자동으로 close 된다.

// 쓸데없는 코드의 작성을 줄이는 것으로 로직에만 집중할 수 있게 도와준다.
PrevioustakeUnlessNextrepeat

Last updated 6 years ago