3

我在 scala 中有一些问题来解决隐式值,并且我在 netbeans 中有神秘的错误消息:

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

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

“类型不匹配:29:错误:类型不匹配;发现:需要 Factory.type(具有基础类型对象工厂):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
}
4

1 回答 1

3

I'm not sure what you are trying to achieve here, but here are few tips:

1) instead of:

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

try this:

implicit object Factory extends GenericFactory { ...

2) Default values for lambdas can only be provided via implicits as far as I know, so instead of:

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

try this:

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

I hope this info is useful.

于 2011-07-29T09:34:24.800 回答