Scala functional composition

I am trying to get currying to work correctly. I have the following:

    def method(x: ByteArrayInputStream)
              (y: ByteArrayOutputStream)
              (z: GZIPOutputStream)
              (func: (ByteArrayInputStream, GZIPOutputStream) => Unit) = {

    .....
    .....

    }

Now, when I call it, I call it like this:

    method(new ByteArrayInputStream("".getBytes("UTF-8"))) 
          (new ByteArrayOutputStream()) 
          (new GZIPOutputStream(_)) 
          (myFunc(_, _))

I understand that in the third parameter, that is, in GZIPOutputStream, when I say _, it will select a value from the second parameter. But he complains that

Type mismatch, expected: GZIPOutputstream, actual: (OutputStream) => GZIPOutputStream

Any clues?

+3
source share
3 answers

I managed to fool a little, and here is what I wanted:

val bytePayload = method(new ByteArrayInputStream(s.getBytes("UTF-8")))(new ByteArrayOutputStream())(writeBytes(_,_))

  def method(bin: ByteArrayInputStream)
            (bos: ByteArrayOutputStream)
            (func: (ByteArrayInputStream, GZIPOutputStream) => Unit): Either[String, Array[Byte]] = {
    val gzip = new GZIPOutputStream(bos)

    try {
      func(bin, gzip)
      gzip.finish
    } catch {
      case e: Exception => Left(e.getMessage)
    } finally {
      bin.close()
      bos.close()
      gzip.close()
    }
    Right(bos.toByteArray)
  }

Although I still handle exceptions, I am somewhat convinced that I am not throwing them.

0
source

I'm not quite sure how to do this ... but here is one solution that mimics what you are looking for

def add(j: Int)(i: Option[Int] = None): Int = j + i.getOrElse(j)
add(5)()

Adds (5) () returns 10 and uses the value of j

0
source

(new GZIPOutputStream(_))

, a GZIPOutputstream, OutputStream GZIPOutputstream

, scala, GZIPOutputstream, . , , .

How to fix this depends on what you are actually trying to do. If you really want to transfer GZIPOutputstream, you need to replace this _with OutputStream.

If your intention is to methodcreate GZIPOutputstreamwith a factory function similar to the one you pass in, you want to change the declared type for z. For instance,

(z: (OutputStream) => GZIPOutputStream)

and then in the body of the method you can say something like z(y)to get GZIPOutputstream. (Or replace ywith some other output stream.)

0
source

All Articles