scala泛型类型推断为nothing
我使用Scalaz的ReaderWriterState编写了以下代码。我的泛型类型参数K在编译期间被推断为Nothing。有人能告诉我发生了什么事吗scala泛型类型推断为nothing,scala,scalaz,Scala,Scalaz,我使用Scalaz的ReaderWriterState编写了以下代码。我的泛型类型参数K在编译期间被推断为Nothing。有人能告诉我发生了什么事吗 object O { type VM = VirtualMachine def getQueue[K, R]: RWS[VM, Map[K, R], EventQueue, Unit] = RWS { case (vm, s) => (Map[K,R](), (), s) } def pro
object O {
type VM = VirtualMachine
def getQueue[K, R]: RWS[VM, Map[K, R], EventQueue, Unit] = RWS {
case (vm, s) => (Map[K,R](), (), s)
}
def processEventSet[K, R](f: Event => R): RWS[VM, Map[K,R], EventQueue, Seq[R]] = RWS {
case (vm, q) =>
val set = q.remove
(Map.empty[K, R], set.eventIterator.toSeq map f, q)
}
def resume[K, R]: RWS[VM, Map[K,R], EventQueue, Seq[R]] = RWS {
case (vm, q) => vm.resume();(Map.empty[K,R], List.empty[R], q)
}
def process(f: Event => Int): RWS[VM, Map[Int, Int], EventQueue, Seq[Int]] = for {
_ <- getQueue
res <- processEventSet(f)
_ <- resume
} yield res
def processT[K, R](f: Event => R): RWS[VM, Map[K,R], EventQueue, Seq[R]] = for {
_ <- getQueue
res <- processEventSet(f)
_ <- resume
} yield res
}
对象O{
类型VM=虚拟机
def getQueue[K,R]:RWS[VM,Map[K,R],EventQueue,Unit]=RWS{
格(vm,s)=>(Map[K,R](),(),s)
}
def processEventSet[K,R](f:Event=>R):RWS[VM,Map[K,R],EventQueue,Seq[R]]=RWS{
案例(vm,q)=>
val set=q.remove
(Map.empty[K,R],set.eventIterator.toSeq映射f,q)
}
def resume[K,R]:RWS[VM,Map[K,R],事件队列,序列[R]=RWS{
case(vm,q)=>vm.resume();(Map.empty[K,R],List.empty[R],q)
}
def进程(f:Event=>Int):RWS[VM,Map[Int,Int],EventQueue,Seq[Int]=for{
_函数
def processEventSet[K, R](f: Event => R): RWS[VM, Map[K,R], EventQueue, Seq[R]]
对于如何推断类型K
,没有任何线索。所有类型都应该可以从函数参数推断
您可能希望显式地提供它,或者创建另一个参数(甚至是隐式的),以允许编译器推断类型。例如:
trait TypeHelper[K,R]
implicit object intHelper extends TypeHelper[Int, Int]
def processEventSet[K, R](f: Event => R)(implicit ev: TypeHelper[K,R]):
RWS[VM, Map[K,R], EventQueue, Seq[R]]
这可能会给编译器提供足够的信息来推断类型。(虽然我还没有测试过。)谢谢你的回答。我试过了,但没有解决问题。根据你的回答,我可以想象如果f是f:K=>R,它应该满足编译器吗?(但在我的情况下不适用。)为了让编译器能够推断类型,它需要一些线索。如果类型出现在参数中,编译器知道参数的类型并可以推断未知的类型参数。然后它们被用来计算结果类型。K
在您的例子中,参数中不存在。因此编译器无法推断它。编译器如何猜测K
应等于?
trait TypeHelper[K,R]
implicit object intHelper extends TypeHelper[Int, Int]
def processEventSet[K, R](f: Event => R)(implicit ev: TypeHelper[K,R]):
RWS[VM, Map[K,R], EventQueue, Seq[R]]