我运行了以下代码,并成功打印出s3Service.createUnsignedObjectUrl方法中的“URL”。我的问题是,变量如何返回并存储到“linkForText”变量中?我读到scala函数通常需要“def”函数中的“:Int”和“return”之类的东西。但我在这里没有看到。商店功能如何才能做到这一点?
package com.justthor
import org.jets3t.service.impl.rest.httpclient.RestS3Service
import org.jets3t.service.security.AWSCredentials
import org.jets3t.service.model.S3Object
import org.jets3t.service.acl.{ AccessControlList, GroupGrantee, Permission }
import java.io.InputStream
object Main extends App{
val classPath = "/"
// upload a simple text file
val textFilename = "test.txt"
val linkForText = store(textFilename, getClass.getResourceAsStream(s"$classPath$textFilename"))
// upload a cat image, taken from http://imgur.com/gallery/bTiwg
// set the content type to "image/jpg"
val imageFilename = "cat.jpg"
val linkForImage = store(imageFilename, getClass.getResourceAsStream(s"$classPath$imageFilename"), "image/jpg")
println(s"Url for the text file is $linkForText")
println(s"Url for the cat image is $linkForImage")
def store(key: String, inputStream: InputStream, contentType: String = "text/plain") = {
val awsAccessKey = "YOUR_ACCESS_KEY"
val awsSecretKey = "YOUR_SECRET_KEY"
val awsCredentials = new AWSCredentials(awsAccessKey, awsSecretKey)
val s3Service = new RestS3Service(awsCredentials)
val bucketName = "test-scala-upload"
val bucket = s3Service.getOrCreateBucket(bucketName)
val fileObject = s3Service.putObject(bucket, {
// public access is disabled by default, so we have to manually set the permission to allow read access to the uploaded file
val acl = s3Service.getBucketAcl(bucket)
acl.grantPermission(GroupGrantee.ALL_USERS, Permission.PERMISSION_READ)
val tempObj = new S3Object(key)
tempObj.setDataInputStream(inputStream)
tempObj.setAcl(acl)
tempObj.setContentType(contentType)
tempObj
})
s3Service.createUnsignedObjectUrl(bucketName,
fileObject.getKey,
false, false, false)
}
}
答案 0 :(得分:1)
推理和scala-isms。
return
类型是从return
值推断的,这是方法/函数中最终语句的结果。
因此,在您的情况下,最后一行返回的内容:s3Service.createUnsignedObjectUrl(...)
是从store
返回的值。并且,由于没有分支,因此将从该值推断返回类型。并且,如果存在分支,那么推论将采用可能的返回类型的最小公分母。