与Actor一起使用时的Scala变量绑定 [英] Scala variable binding when used with Actors

查看:269
本文介绍了与Actor一起使用时的Scala变量绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Scala很新。
我试图理解如何/如果scala在闭包作为消息的一部分传递给Actor时进行动态绑定。

I am fairly new to Scala. I am trying to understand how/if scala does dynamic binding when a closure is passed as part of a message to an Actor.

我使用Akka 1.2和Scala 2.9。

I am using Akka 1.2 with Scala 2.9.

我有以下代码段(修改自http://gleichmann.wordpress.com/2010/11/15/functional-scala-closures/

I have the following code segment (modified from http://gleichmann.wordpress.com/2010/11/15/functional-scala-closures/)

var minAge = 18
val isAdult = (age: Int) => age >= minAge

actor ! answer(19, isAdult) 
minAge = 20
actor ! answer(19, isAdult)

在actor方面,它只是应用isAdult到第一个参数,结果。
因为Scala使用动态绑定(所以我被告知),我会期望

On the actor side, it simply applies isAdult to the first parameter and prints the result. Since Scala uses dynamic binding (so I was told), I would have expected

true
false

但不知何故,结果是

false
false

静态绑定变量,并取18作为两个应答消息的minAge的值?在消息中使用闭包时是否有保持动态绑定行为的方法?

So is it true that scala is binding the variable statically and taking 18 as the value of minAge for both answer messages? Is there a way to keep the dynamic binding behavior while using closures in messages?

谢谢!

推荐答案

您对闭包的理解是正确的。它正在进行动态绑定,但您正在引入并发问题。闭包是绑定到可变数据,使闭包可变。当您在角色之间传递严格不可变的数据时,actor模型只解决并发问题。你可以按照表面上的时间顺序写它,但是actor调度器改变事件的顺序。因为isAdult是可变的,重新排序改变了结果。

Your understanding of closures is correct. It is doing dynamic binding however you are introducing concurrency issues. The closure is binding to mutable data which makes the closure mutable. The actor model only solves concurrency issues when you pass strictly immutable data between actors. You may write it in a seemingly chronological order but the actor scheduler changes the order of events. And since isAdult is mutable the reordering changes the results.

actor ! answer(19, isAdult) // message put in actor queue
minAge = 20
actor ! answer(19, isAdult) // message put in actor queue
// later...
// actor handles answer(19, isAdult)
// actor handles answer(19, isAdult)

这篇关于与Actor一起使用时的Scala变量绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆