3

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 ?

4
  • The simplest solution would be to define C as a trait instead of a type alias : trait C extends A[String,Int] with B[String,Double]. Commented Oct 29, 2015 at 16:41
  • I know i can do that . but i am intrested in why it happens Commented Oct 29, 2015 at 16:49
  • 2
    The generic part is a red herring here—you'd see the same result with trait A and trait B. Commented Oct 29, 2015 at 17:15
  • OK, so what is the problem ? how can i solve it without traits? i want to dive into it and understand the meaning of what i write. what is the difference between trait and type ? Commented Oct 29, 2015 at 17:31

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.