如何在Scala中实例化由type参数表示的类型的实例 [英] How to instantiate an instance of type represented by type parameter in Scala

查看:259
本文介绍了如何在Scala中实例化由type参数表示的类型的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例子:

$ $ p $ import scala.actors._
import Actor._

class BalanceActor [T<:Actor]扩展Actor {
val workers:Int = 10

private lazy val actors = new Array [T](workers)

覆盖def start()= {
for(i < - 0 to(workers - 1)){
//以下错误:需要classtype,但T找到
actors(i) = new T
actors(i).start
}
super.start()
}
//错误如下:方法mailboxSize无法在T $ b中访问$ b def workerMailboxSizes:List [Int] =(actors map(_.mailboxSize))。toList



注意第二个错误表明它知道演员项目是T,但不是T是actor的一个子类,正如类泛型定义中的约束一样。



这段代码如何纠正才能工作(使用Scala 2.8)?

解决方案

编辑 - 道歉,我只注意到你的第一个错误。没有办法在运行时实例化 T ,因为在编译程序时(通过类型擦除),类型信息会丢失。



您必须通过一些工厂来实现构建:

  class BalanceActor [T<:Actor](val fac:()=> T)扩展Actor {
val workers:Int = 10

private lazy val actors = new Array [T] (i <= 0到(workers-1)){
actors(i)= fac()//($()){
覆盖def start()= {
//使用工厂方法实例化T
actors(i).start
}
super.start()
}
}

这可能与一些演员 CalcActor 一起使用,如下所示:

  val ba = new BalanceActor [CalcActor]({()=> new CalcActor})
ba.start

另外:您可以使用,直到而不是

  val size = 10 
0直到大小//相当于:
0到(大小-1)


example:

import scala.actors._  
import Actor._  

class BalanceActor[T <: Actor] extends Actor {  
  val workers: Int = 10  

  private lazy val actors = new Array[T](workers)  

  override def start() = {  
    for (i <- 0 to (workers - 1)) {  
      // error below: classtype required but T found  
      actors(i) = new T  
      actors(i).start  
    }  
    super.start()  
  }  
  // error below:  method mailboxSize cannot be accessed in T
  def workerMailboxSizes: List[Int] = (actors map (_.mailboxSize)).toList  
.  
.  
.  

Note the second error shows that it knows the actor items are "T"s, but not that the "T" is a subclass of actor, as constrained in the class generic definition.

How can this code be corrected to work (using Scala 2.8)?

解决方案

EDIT - apologies, I only just noticed your first error. There is no way of instantiating a T at runtime because the type information is lost when your program is compiled (via type erasure)

You will have to pass in some factory to achieve the construction:

class BalanceActor[T <: Actor](val fac: () => T) extends Actor {
  val workers: Int = 10

  private lazy val actors = new Array[T](workers)

  override def start() = {
    for (i <- 0 to (workers - 1)) {
      actors(i) = fac() //use the factory method to instantiate a T
      actors(i).start
    }
    super.start()
  }
} 

This might be used with some actor CalcActor as follows:

val ba = new BalanceActor[CalcActor]( { () => new CalcActor } )
ba.start

As an aside: you can use until instead of to:

val size = 10
0 until size //is equivalent to:
0 to (size -1)

这篇关于如何在Scala中实例化由type参数表示的类型的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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