相关疑难解决方法(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中的类型投影?

问题陈述

考虑一个T包含抽象类型成员的类型A:

trait T {
  type A
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个类T0 <: T作为类型参数,但专注于类型投影 T0#A.例如,在下面,该方法foo可以是专用的吗?

class Foo[T0 <: T] {
  def foo(a: T0#A, f: T0#A => T0#A) = f(a)
}
Run Code Online (Sandbox Code Playgroud)

需要注意的是注释T0@specialized不会达到预期的效果.是否有一种专门foo研究类型投影的好方法T#A

有限的解决方案:从具有额外参数的专用父类继承

在这种特殊情况下,这是一种专门研究的方法T0#A:

trait SpecializedFoo[@specialized A0, T0 <: T] {
  def foo(a: A0, f: A0 => A0) = f(a)
}
class Foo2[T0 <: T] extends SpecializedFoo[T0#A, T0]
Run Code Online (Sandbox Code Playgroud)

通过继承专门的父类SpecializedFoo,我们确保它Foo2.foo是专门的.

验证专业化 …

types scala

10
推荐指数
1
解决办法
924
查看次数

如何定义循环类型定义?

这不是有效的类型定义:

scala>  type Addable = { def +(subject: Addable) }
<console>:4: error: illegal cyclic reference involving type Addable
        type Addable = { def +(subject: Addable) }
Run Code Online (Sandbox Code Playgroud)

这可以用scala表达吗?

scala

6
推荐指数
1
解决办法
1379
查看次数

Scala:解决"非法循环引用"

我正在尝试实现一个基于HashMap的树,该树支持给定根密钥的O(1)子树查找.为了达到这个目标,我正在努力做到以下几点:

scala> type Q = HashMap[Char, Q]
<console>:6: error: illegal cyclic reference involving type Q
       type Q = HashMap[Char, Q]
                          ^
Run Code Online (Sandbox Code Playgroud)

所以问题是,有没有办法让我做一些这样的事情而不诉诸丑陋HashMap[Char, Any]的随后的价值观HashMap[Char, Any]

现在,我也看到我可以使用类似下面的内容来避免循环引用错误,它甚至可能更干净 - 但是找到如何正确地执行它的第一种方式很好,只是为了教育价值.

import collections.mutable.HashMap

class LTree {
  val children = new HashMap[Char, LTree]
}
Run Code Online (Sandbox Code Playgroud)

谢谢一堆.

tree types scala

6
推荐指数
1
解决办法
5061
查看次数

标签 统计

scala ×5

types ×3

tree ×1

type-inference ×1