简体   繁体   中英

Scala define type from multiple generic traits

How can I fix this code :

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
}

The exception i got is :

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

Any Idea how to solve that and what is the reason for that ?

My guess why it doesn't work (and probably shouldn't): type C = ... defines something which is not a class type, I wonder what it is. But when you pass it to new it expects new class_type with trait_type ... , so you are trying to replace only one thing, namely class_type with C . If you define C without with it will work.

You can also write:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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