Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"using" function

I've defined 'using' function as following:

def using[A, B <: {def close(): Unit}] (closeable: B) (f: B => A): A =   try { f(closeable) } finally { closeable.close() } 

I can use it like that:

using(new PrintWriter("sample.txt")){ out =>   out.println("hellow world!") } 

now I'm curious how to define 'using' function to take any number of parameters, and be able to access them separately:

using(new BufferedReader(new FileReader("in.txt")), new PrintWriter("out.txt")){ (in, out) =>   out.println(in.readLIne) } 
like image 372
Albert Cenkier Avatar asked Mar 07 '10 10:03

Albert Cenkier


People also ask

What is the use of functions?

A function is simply a “chunk” of code that you can use over and over again, rather than writing it out multiple times. Functions enable programmers to break down or decompose a problem into smaller chunks, each of which performs a particular task.

What is the use of function explain with example?

An example of a simple function is f(x) = x2. In this function, the function f(x) takes the value of “x” and then squares it. For instance, if x = 3, then f(3) = 9. A few more examples of functions are: f(x) = sin x, f(x) = x2 + 3, f(x) = 1/x, f(x) = 2x + 3, etc.

WHAT IS function and use of function?

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times.


1 Answers

Starting Scala 2.13, the standard library provides a dedicated resource management utility: Using.

More specifically, the Using#Manager can be used when dealing with several resources.

In our case, we can manage different resources such as your PrintWriter or BufferedReader as they both implement AutoCloseable, in order to read and write from a file to another and, no matter what, close both the input and the output resource afterwards:

import scala.util.Using import java.io.{PrintWriter, BufferedReader, FileReader}  Using.Manager { use =>    val in  = use(new BufferedReader(new FileReader("input.txt")))   val out = use(new PrintWriter("output.txt"))    out.println(in.readLine) } // scala.util.Try[Unit] = Success(()) 
like image 119
Xavier Guihot Avatar answered Oct 10 '22 09:10

Xavier Guihot