相关疑难解决方法(0)

为什么Scala在嵌套类型参数时不能完全推断类型参数?

请考虑以下Scala代码:

abstract class A
abstract class B[T <: A]
class ConcreteA extends A
class ConcreteB extends B[ConcreteA]

class Example[U <: B[T], T <: A]( resolver: U )
object Test {
    new Example( new ConcreteB )
}
Run Code Online (Sandbox Code Playgroud)

最后一行new Example( new ConcreteB )无法编译,出现以下错误:

错误:推断类型参数[ConcreteB,Nothing]不符合类Example的类型参数bounds [U <:B [T],T <:A]

但是ConcreteB有解决U T的所有必要数据.我在这里缺少什么?

scala

13
推荐指数
2
解决办法
6488
查看次数

在Scala中输入Nothing的类型

当我尝试编译小例子时:

trait Foo[A,B] {
  type F[_,_]
  def foo(): F[A,B]
}

class Bar[A,B] extends Foo[A,B] {
  type F[D,E] = Bar[D,E]
  def foo() = this
}

object Helper {
  def callFoo[A,B,FF <: Foo[A,B]]( f: FF ): FF#F[A,B] =
    f.foo()
}

object Run extends App {
  val x = new Bar[Int,Double]
  val y = Helper.callFoo(x)
  println( y.getClass )
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

[error] src/Issue.scala:20: inferred type arguments
[Nothing,Nothing,issue.Bar[Int,Double]] do not conform to method callFoo's type
parameter bounds [A,B,FF <: issue.Foo[A,B]]
[error]       val y = Helper.callFoo(x) …
Run Code Online (Sandbox Code Playgroud)

types scala type-inference

12
推荐指数
1
解决办法
1900
查看次数

在Scala中,是否有缩写泛型类型的简写的简写?

我想调用Scalaz的pure方法将值放入State monad.以下作品:

type IntState[A] = State[Int, A]
val a = "a".pure[IntState]
a(1)
    (Int, java.lang.String) = (1,a)
Run Code Online (Sandbox Code Playgroud)

我也可以删除类型别名(感谢Scalaz的Pure.scala):

val a = "a".pure[({type T[A]=State[Int,A]})#T]
a(1)
    (Int, java.lang.String) = (1,a)
Run Code Online (Sandbox Code Playgroud)

但这非常笨重.是否有更短的方法来合成这样的类型?就像函数文字的占位符语法一样,有类似的东西:

"a".pure[State[Int, *]]
Run Code Online (Sandbox Code Playgroud)

generics scala scalaz

11
推荐指数
2
解决办法
752
查看次数

Scala无法推断出正确的类型参数

背景信息:我目前正在尝试建立一个包含几种不同搜索算法的通用图形库(我已经开始使用Dijkstra).我已经设置了一些特征来表示在某些类型的图中可以找到的方法(例如加权,定向):

trait GraphOps[V,E] { ... }
trait WeightedGraphOps[V,E] extends GraphOps[V,E] { ... }
trait DirectedGraphOps[V,E] extends GraphOps[V,E] { ... }
object GraphOps{
  def Dijkstra[V,E,G <: WeightedGraphOps[V,E] with DirectedGraphOps[V,E]](graph:G, start:V) = { ... }
}
Run Code Online (Sandbox Code Playgroud)

在其他地方,我有一个类作为加权有向图的具体实现,我想运行Dijkstra的算法:

class GraphMap[T](...)
extends scala.collection.mutable.Map[Position,T]
with WeightedGraphOps[Position,Edge] with DirectedGraphOps[Position,Edge] { ... }
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试测试它时:

val graph = new GraphMap[Int](...)
val (dist, prev) = GraphOps.Dijkstra(graph, Position(0,0))
Run Code Online (Sandbox Code Playgroud)

问题:我在编译过程中遇到以下错误:error: inferred type arguments [com.dylan.data.Position,Nothing,com.dylan.data.GraphMap[Int]] do not conform to method Dijkstra's type parameter bounds [V,E,G <: com.dylan.data.WeightedGraphOps[V,E] with com.dylan.data.DirectedGraphOps[V,E]] …

generics scala generic-type-argument

5
推荐指数
1
解决办法
918
查看次数