Forward reference extends over definition of value

2019-07-17 10:00发布

问题:

i have some problem in scala to resolve implicit values, and i have the cryptic error message in netbeans :

"error : Forward reference extends over definition of value ..."

or in the scala console i have an other error message

"type mistmatch :29: error: type mismatch; found : Factory.type (with underlying type object Factory) required: GenericFactory"

Some description of my class and main function :

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)
}

I have 2 problem because 1) i can pass an object in argument of class A, so i define an abstract class to pass this abstract class, but that not work here :/ 2) After that, my implicit value defined into class A is not recognized, and fail with error message.

Do you have an idea or an answer to resolve this problem ?

Edit 1

I update the code with help of agisteel, it's ok, code running :)

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:

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.