scala - 如何使辅助类型编译?
问题描述
我有以下带有 aux 类型的示例,但无法编译:
trait Foo[A] {
type B
def value: B
}
object Foo {
type Aux[A0, B0] = Foo[A0] { type B = B0}
implicit def footInt = new Foo[Int] {
override type B = String
override def value = "Hey!"
}
implicit def fooString = new Foo[String] {
override type B = Boolean
override def value = true
}
}
import cats._
import cats.implicits._
object App {
def main(args: Array[String]): Unit = {
val x: Id[String] = "Hello"
println(foo(1))
println(foo("Hello"))
println(fooAux(1)(x))
}
def foo[T](t: T)(implicit f: Foo[T]): f.B = f.value
def fooAux[T, R] (t: T) (implicit f: Foo.Aux[T, R], id: Id[R]) : R = f.value
}
编译抱怨:
Error:(15, 22) not enough arguments for method fooAux: (implicit f: com.sweetsoft.Foo.Aux[Int,R], implicit id: cats.Id[R])R.
Unspecified value parameter id.
println(fooAux(1)(x))
Error:(21, 55) parameter value id in method fooAux is never used
def fooAux[T, R] (t: T) (implicit f: Foo.Aux[T, R], id: Id[R]) : R = f.value
Error:(4, 23) Unused import
import cats.implicits._
我究竟做错了什么?
解决方案
它编译时稍作修改:
trait Foo[A] {
type B
def value: B
}
object Foo {
type Aux[A0, B0] = Foo[A0] { type B = B0 }
implicit val footInt = new Foo[Int] {
override type B = String
override def value = "Hey!"
}
implicit def fooString = new Foo[String] {
override type B = Boolean
override def value = true
}
}
object App {
type Id[X] = X
def main(args: Array[String]): Unit = {
implicit val x: Id[String] = "Hello"
println(foo(1))
println(foo("Hello"))
println(fooAux(1))
}
def foo[T](t: T)(implicit f: Foo[T]): f.B = f.value
def fooAux[T, R] (t: T) (implicit f: Foo.Aux[T, R], id: Id[R]): R = id
}
第一个错误很清楚:第二个参数列表fooAux
需要两个参数,但你只传递了一个x
.
第二个错误信息也很普通:你永远不会使用id
.
只要您提供隐式String
(我假设您想要x
隐式),其余的工作几乎是原样的。
推荐阅读
- python - 如何将列表附加到另一个列表
- javascript - 在 WKWebView 中注入 javascript 以获取单击图像的 src 属性
- php - Laravel“未定义的索引......”Foreach循环中的错误
- angular - 无法使用角度更改 http post 请求中的 Content-Type
- c# - 如何使用 Azure Batch 中的 Key Vault 进行身份验证
- ruby-on-rails - ActionView::Template::Error: nil:NilClass 的未定义方法 `<'
- arrays - 以特定方式创建由矩阵重复组成的 3D 数组
- vue.js - 将 MSAL 访问令牌转换为 Hapi JWT 令牌
- sql - 根据预订日期获取免费车辆的 SQL 查询
- linux - 发现 /proc/mounts 的“真实”大小