我发现Scala总是对任何东西都有"自然的解释".总是像"哦,但这只是一个函数被调用此函数和该对象与此参数".从某种意义上说,我们从其他语言中知道它并不是真正的编译器魔法.
我的问题是在以下代码中使用的< -运算符:
for(i <- 0 to 10) println(i)
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我可以看到它被重写为:
0.to(10).foreach((i:Int)=>println(i))
Run Code Online (Sandbox Code Playgroud)
但这并没有解释我如何进入foreach函数内的匿名函数.在你写i的时候,它不是一个对象,也不是一个声明的变量.那是什么呢,它是如何被带到foreach的内部的呢?
我的猜测是,我终于发现了一些实际上是编译魔术的东西
谢谢你的时间.
为了澄清,我的问题是:如何做的< -在代码的第一线操作人员的工作,因为我不上它可作为函数调用的对象.
参考:
Scala 在scala控制器中返回关键字
处理错误
EDIT3
这是"最终"解决方案,再次感谢Dan Burton.
def save = Action { implicit request =>
val(orderNum, ip) = (generateOrderNum, request.remoteAddress)
val result = for {
model <- bindForm(form).right // error condition already json'd
transID <- payment.process(model, orderNum) project json
userID <- dao.create(model, ip, orderNum, transID) project json
} yield (userID, transID)
}
Run Code Online (Sandbox Code Playgroud)
然后是pimp'd Either项目方法,放在你的应用程序的某个地方(在我的例子中,一个impbits特性,sbt root和子项目扩展了它们的基础包对象:
class EitherProvidesProjection[L1, R](e: Either[L1, R]) {
def project[L1, L2](f: L1 => L2) = e match {
case Left(l:L1) => Left(f(l)).right
case Right(r) => Right(r).right …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个整洁的结构,以便理解基于未来的业务逻辑.这是一个示例,其中包含基于异常处理的工作示例:
(for {
// find the user by id, findUser(id) returns Future[Option[User]]
userOpt <- userDao.findUser(userId)
_ = if (!userOpt.isDefined) throw new EntityNotFoundException(classOf[User], userId)
user = userOpt.get
// authenticate it, authenticate(user) returns Future[AuthResult]
authResult <- userDao.authenticate(user)
_ = if (!authResult.ok) throw new AuthFailedException(userId)
// find the good owned by the user, findGood(id) returns Future[Option[Good]]
goodOpt <- goodDao.findGood(goodId)
_ = if (!good.isDefined) throw new EntityNotFoundException(classOf[Good], goodId)
good = goodOpt.get
// check ownership for the user, checkOwnership(user, good) returns Future[Boolean]
ownership <- goodDao.checkOwnership(user, …Run Code Online (Sandbox Code Playgroud) 给出以下类型:
sealed trait Pet {
val name: String
}
case class Dog(override val name: String) extends Pet
case class Cat(override val name: String) extends Pet
sealed trait Error
case object DBConnection extends Error
case object NoResults extends Error
Run Code Online (Sandbox Code Playgroud)
我们编写了一个按名称搜索宠物的函数.
def foo(petName: String): Either[Error, Pet] = {
val results: Either[Error, List[Pet]] = ??? // does not matter
val foundPet: Option[Pet] = results match {
case left @ Left(_) => None
case Right(ps) => ps.find(_.name == petName)
}
foundPet match {
case …Run Code Online (Sandbox Code Playgroud)