问题描述
我在 Scala 中遇到了一些问题来解决隐式值,并且我在 netbeans 中有一个神秘的错误消息:
i have some problem in scala to resolve implicit values, and i have the cryptic error message in netbeans :
错误:前向引用扩展了值的定义......"
或在 Scala 控制台中,我有其他错误消息
or in the scala console i have an other error message
"类型不匹配:29:错误:类型不匹配;找到:Factory.type(具有基础类型对象工厂)需要:通用工厂"
对我的类和主要功能的一些描述:
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)
}
我有两个问题,因为 1) 我可以在 A 类的参数中传递一个对象,所以我定义了一个抽象类来传递这个抽象类,但这在这里不起作用:/2) 之后,我定义到 A 类中的隐式值无法识别,并失败并显示错误消息.
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 ?
我在 agisteel 的帮助下更新了代码,没关系,代码正在运行 :)
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
}
推荐答案
我不确定你在这里想要达到什么目的,但这里有一些提示:
I'm not sure what you are trying to achieve here, but here are few tips:
1) 而不是:
implicit val factory = Factory
object Factory extends GenericFactory { ...
试试这个:
implicit object Factory extends GenericFactory { ...
2) 据我所知,lambda 的默认值只能通过隐式提供,而不是:
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, ...
试试这个:
implicit val function: Random => Double = arpng => arpng.nextFloat
class A (implicit rate: Random => Double) ( ...
我希望这些信息有用.
这篇关于前向参考扩展了价值问题的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!