curiousengineer
curiousengineer

Reputation: 2607

type keyword in scala file upload exampe

type FilePartHandler[A] = FileInfo => Accumulator[ByteString, FilePart[A]]

def handleFilePartAsFile: FilePartHandler[File] = {
    case FileInfo(partName, filename, contentType) =>
    val perms = java.util.EnumSet.of(OWNER_READ, OWNER_WRITE)
    val attr = PosixFilePermissions.asFileAttribute(perms)
    val path = Files.createTempFile("multipartBody", "tempFile", attr)
    val file = path.toFile
    val fileSink = FileIO.toFile(file)
    val accumulator = Accumulator(fileSink)
    accumulator.map { case IOResult(count, status) =>
      FilePart(partName, filename, contentType, file)
    }(play.api.libs.concurrent.Execution.defaultContext)
}

I have copied the above code from Play file upload example. I am having a hard time with syntax of typekeyword. If I say something like this type mytype = Int => String. I can use it say like below

def method2(f:mytype) = "20"
def f(v:Int) = "hello"
method2(f)

But I based on whatever I understand, I am at total loss of how the following syntax is being used in the method handleFilePartAsFile and what does it even mean?

type FilePartHandler[A] = FileInfo => Accumulator[ByteString, FilePart[A]]

Upvotes: 0

Views: 37

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170713

The idea is exactly the same. You just have a type parameter (like you've probably seen on classes and methods before) which can be substituted by any type, so e.g. FilePartHandler[File] is FileInfo => Accumulator[ByteString, FilePart[File]] and you could write handleFilePartAsFile as

def handleFilePartAsFile: FileInfo => Accumulator[ByteString, FilePart[File]] = { ...

You can think of type synonyms with parameters as functions from types to types.

Upvotes: 1

Related Questions