繁体   English   中英

Scala从多个通用特征定义类型

[英]Scala define type from multiple generic traits

我该如何修复此代码:

trait A[A,B]{
  def f(a:A):B
}
trait B[A,B]{
  def g(a:A):B
}

type C = A[String,Int] with B[String,Double]

//works fine
new A[String,Int] with B[String,Double] {
  def f(a:String):Int = 1
  def g(a:String):Double = 2.0
}

//error
new C {
  def f(a:String):Int = 1
  def g(a:String):Double = 2.0
}

我得到的例外是:

Error:(41, 6) class type required but A$A42.this.A[String,Int] with A$A42.this.B[String,Double] found 
new C {
    ^

任何想法如何解决这个问题,原因是什么?

我的猜测为什么它不起作用(也许不应该): type C = ...定义了一个不是类类型的东西,我想知道它是什么。 但是当你把它传递给new它需要new class_type with trait_type ... ,所以你试图只替换一个东西,即class_typeC 如果您定义C而不with它将起作用。

你也可以写:

type C1 = A[String,Int]
type C2 = B[String,Double]
new C1 with C2 {
  def f(a:String):Int = 1
  def g(a:String):Double = 2.0
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM