我在scala中解决隐式值有一些问题,并且我在netbeans中有神秘的错误信息:
"error:前向引用扩展了值的定义…"
或者在scala控制台中,我有另一个错误消息
"type mistmatch:29: error: type mismatch;发现:工厂。需要的类型(具有底层类型对象工厂):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)
}
我有两个问题,因为1)我可以在类A的参数传递对象,所以我定义了一个抽象类来传递这个抽象类,但这在这里不起作用:/2)之后,我定义到A类的隐式值不能被识别,并失败,并显示错误信息。
你有解决这个问题的想法或答案吗?编辑1
我在agsteel的帮助下更新了代码,没关系,代码正在运行:)
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)代替:
implicit val factory = Factory
object Factory extends GenericFactory { ...
试试这个:
implicit object Factory extends GenericFactory { ...
2)据我所知,lambda的默认值只能通过隐式提供,因此,而不是:
class A (rate: Random => Double = aprng => aprng.nextFloat, ...
试试这个:
implicit val function: Random => Double = arpng => arpng.nextFloat
class A (implicit rate: Random => Double) ( ...