在Scala中向函数发送消息 [英] Sending messages to functions in Scala

查看:147
本文介绍了在Scala中向函数发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Bruce Tate的 七周内七种语言我很难理解他的实现 sizer.scala (Scala:第3天)。特别的,考虑下面的Singleton对象

I'm working my way through Bruce Tate's Seven Languages in Seven Weeks and am having a hard time understanding his implementation of sizer.scala (Scala: Day 3). In particular, consider the following Singleton object

object PageLoader {
    def getPageSize(url : String) = Source.fromURL(url).mkString.length
}

计算由 urls 数组给出的每个网页中的字符数。

and the following method that, using actors, calculates the number of characters in each web page given by the urls array.

def getPageSizeConcurrently() = {
    val caller = self

    for(url <- urls) {
        actor { caller ! (url, PageLoader.getPageSize(url)) }
    }

    for(i <- 1 to urls.size) {
        receive {
            case (url, size) =>
                println("Size for " + url + ": " + size)
        }
    }
}




  1. 自我是指什么? getPageSizeConcurrently 自己是否可以引用某个功能?

  2. 假设自己 code> getPageSizeConcurrently ,这是否被认为是在斯卡拉世界很标准?为什么要将消息发送到函数而不是对象,反之亦然?

  1. What does self refer to? getPageSizeConcurrently? Is it possible for self to refer to a function?
  2. Assuming that self does refer to getPageSizeConcurrently, is this considered to be pretty standard in the Scala world? Why send messages to a function instead of an object, or vice versa?

UPDATE:问题只使用自身一次,但它开始于以下 import 语句。

UPDATE: The code in question only uses self once, but it does start with the following import statements.

import scala.io._
import scala.actors._
import Actor._

查看 Scala API a>,看起来 Actor singleton对象有一个 self 方法。即使这是 self 分配给调用,虽然,我不明白为什么

Looking through the Scala API, it appears that the Actor singleton object has a self method. Even if that's the self assigned to caller, though, I don't see why the receive block would be executed.

推荐答案

在Actor配套对象上有一个自我方法。从 scaladoc

There is a self method on the Actor companion object. From the scaladoc:


返回当前执行的actor。

Returns the currently executing actor. Should be used instead of this in all blocks of code executed by actors.

我猜你的代码已经导入了Actor对象,并且它是你的代码正在调用的Actor对象的自我方法。这样你可以获得对你所在主actor线程的引用,并且开始获取页面大小的匿名actor可以将消息发送回你所在的线程。

I'm guessing that your code has imported the Actor object, and that it is the self method on the Actor object your code is calling. This way you get a reference to the main actor thread you're in, and the anonymous actors you start to get page size can send the message back to the thread you're in.

这篇关于在Scala中向函数发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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