前向参考扩展了价值问题的定义

时间:2011-07-29 08:43:39

标签: scala object arguments implicit forward-reference

我在scala中遇到一些问题来解决隐式值,我在netbeans中有一个神秘的错误信息:

  

“错误:前向引用扩展了值的定义......”

或在scala控制台中我有其他错误消息

  

“type mistmatch:29:error:type mismatch; found:   Factory.type(带底层类型对象Factory)必需:   GenericFactory“

我班级和主要功能的一些描述:

import java.util.Random

//////////
// Main //

//Implicit random for all classes and object
implicit val aprng = new Random

//Implicit object Factory used in other class
implicit val factory = Factory

abstract class GenericFactory {
def build 
}

object Factory extends GenericFactory{
def build = println("return factory")
}

class A (rate: Random => Double = aprng => aprng.nextFloat, val factory : GenericFactory) {

  def this(rate : Double, factory : GenericFactory) = this( _ => rate, factory)

  def operate(genomes: IndexedSeq[Int])(implicit aprng: Random) = { 
println("calculate genomes with aprng random values")}
}

object B{
val instanceOfA = new A(rate => 0.5d,factory)
}

我有2个问题因为1)我可以在A类的参数中传递一个对象,所以我定义了一个抽象类来传递这个抽象类,但是这里不起作用:/ 2)之后,我无法识别定义到类A中的隐式值,并且失败并显示错误消息。

您有解决此问题的想法或答案吗?

编辑1

我在agisteel的帮助下更新代码,没关系,运行代码:)

import java.util.Random

//////////
// Main //

//Implicit random for all classes and object
implicit val aprng = new Random
implicit val function: Random => Double = arpng => arpng.nextFloat

abstract class GenericFactory 
{
  def build = println("build")
}

implicit object Factory extends GenericFactory
{
  def build = println("return factory")
}

class A (implicit rate: Random => Double, implicit val factory : GenericFactory) {

  //def this(rate : Double, factory : GenericFactory) = this( _ => rate, factory)

  def operate(genomes: IndexedSeq[Int])(implicit aprng: Random) = { 
    println("calculate genomes with aprng random values")}
}

object B{
val instanceOfA = new A
}

1 个答案:

答案 0 :(得分:3)

我不确定你在这里想要达到的目标,但这里有一些提示:

1)而不是:

implicit val factory = Factory
object Factory extends GenericFactory { ...

试试这个:

implicit object Factory extends GenericFactory { ...

2)据我所知,lambdas的默认值只能通过implicits提供,所以代替:

class A (rate: Random => Double = aprng => aprng.nextFloat, ...

试试这个:

implicit val function: Random => Double = arpng => arpng.nextFloat
class A (implicit rate: Random => Double) ( ...

我希望这些信息很有用。