Reputation: 1989
I have the following code:
case class A[T](a:T, b:Array[Int])
object A {
def apply[T](aa:T):A[T] = A(aa, Array(1, 2, 3))
}
trait TLike[T]
case class TSample1[T](str:String) extends TLike[T]
Why if I instantiate from A
with type I get the following error:
object tmp extends App{
val a = A[TLike[TSample1]](TSample1("dumb"))
}
Error:
overloaded method value apply with alternatives:
(a: TLike[TSample1],b: Array[Int])A[TLike[TSample1]] <and>
(aa: TLike[TSample1])A[TLike[TSample1]]
cannot be applied to (TSample1[Nothing])
val a = A[TLike[TSample1]](TSample1("dumb"))
But if I just leave it to Scalac it works correctly:
object tmp extends App{
val a = A(TSample1("dumb"))
}
Upvotes: 1
Views: 3584
Reputation: 16298
Actually it's hard to understand what you are trying to achieve here, but you should consider two things:
TSample
take arguments, so Tlike[TSample]
is pretty complex typeTSample.apply
what type parameter T
should be, it would be inferred to Nothing
by default This for example would compile
A[TLike[TSample1[_]]](TSample1[TSample1[_]]("dumb"))
Whis would also:
A[TLike[Nothing]](TSample1("dumb"))
Latter is equivalent for
A(TSample1("dumb"))
without any type specification
Upvotes: 0
Reputation: 3591
If we start with your case that compiles, you call object A
's apply
method, which works as expected.
If we later go to the example that doesn't compile and look at the compile error:
Main.scala:10: error: overloaded method value apply with alternatives:
(a: TLike[TSample1],b: Array[Int])A[TLike[TSample1]] <and>
(aa: TLike[TSample1])A[TLike[TSample1]]
cannot be applied to (TSample1[Nothing])
val a = A[TLike[TSample1]](TSample1("dumb"))
^
one error found
It says that it finds two apply
methods, one which you defined and one which is the standard case class
method (read more about that if you need to).
I'm guessing you try to call this method:
def apply[T](aa:T):A[T] = A(aa, Array(1, 2, 3))
However you can't call the A
object's apply function with a template. The other call doesn't match since it also needs an array. Also the types TLike[TSample1]
is not equal to TSample1
.
Upvotes: 1