joshua-r2
10/20/2017 - 2:34 PM

Inline Function

Inline Functions are not invocated until they are used elsewhere. This significantly reduces overhead, especially if nested functions are being used in a For loop.


//Note the "inline" prefix, meaning this function isn't invoked until called
inline fun <T : AutoClosable, U> withResource(resource: T, fn: (T) -> U): U{

  try{
   return fn(resource)
  }finally{
    resource.close()
  }
}

fun CharacterCount(fileName: String): Int {
  val input = Files.newInputStream(Paths.get(filename))
  
  return withResource(input){
    input.buffered().reader().readText().length()
  }
  
}

/*
The actual bytecode the compiler uses is this, due to the inline:

fun CharacterCount(fileName: String): Int {
  val input = Files.newInputStream(Paths.get(filename))
  
  return withResource(input){
    
  }
  
    try{
      return input.buffered().reader().readText().length()
  }finally{
      input.close()
  }
  
}
*/

fun main(args: Array<String>){

for (i in args.indicies()){

  println(CharacterCount(args))

}




}