- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Type parameter, collection and return type
Thu, 2012-02-09, 17:55
Hi,
why is the following code producing the compiler error 'type mismatch;
found : Traversable[Any] required: C'? The type of the collection
doesn't change and therefore it is a C. If I ommit the ':C' of the
method than the return type is inferred to Traversable[Any].
class Test[C <: Traversable[Any] : Manifest](collection: C)
{
def test(): C = collection.filter(e => e == e)
}
(new Test(Set[String]())).test
Thu, 2012-02-09, 18:41
#2
Re: Type parameter, collection and return type
def worksLikeThis[A, B[A] <: Traversable[A]](c: B[A]) = c.filter(e => true)
Am 09.02.2012 17:55, schrieb Ka Ter:
> Hi,
>
> why is the following code producing the compiler error 'type mismatch;
> found : Traversable[Any] required: C'? The type of the collection
> doesn't change and therefore it is a C. If I ommit the ':C' of the
> method than the return type is inferred to Traversable[Any].
>
> class Test[C <: Traversable[Any] : Manifest](collection: C)
> {
> def test(): C = collection.filter(e => e == e)
> }
>
> (new Test(Set[String]())).test
>
Sat, 2012-02-18, 23:21
#3
Re: Type parameter, collection and return type
Ok, I tried two variants, but none of them compile:
1)
class Element
def test[C <: Traversable[Element], B, That](traversable: C)(
implicit cbf: CanBuildFrom[C, B, That]): That =
traversable.map(a => a)(cbf)
test(Set[Element]()).contains(new Element)
2)
class Element2
def test2[E <: Element, C[E] <: Traversable[E], B,
That](traversable: C[E])(
implicit cbf: CanBuildFrom[C[E], B, That]): That =
traversable.map(a => a)(cbf)
test2(Set[Element]()).contains(new Element2)
The problem is in both cases the following:
1) type mismatch; found :
scala.collection.generic.CanBuildFrom[C,B,That] required:
scala.collection.generic.CanBuildFrom[Traversable[Element],Element,That]
2) type mismatch; found :
scala.collection.generic.CanBuildFrom[C[E],B,That] required:
scala.collection.generic.CanBuildFrom[Traversable[E],E,That]
NewTestQuery.scala
How can I get the method test to emit a Set thus I can use the contains
Method?
Best Regards
Ka Ter
Am 09.02.2012 18:38, schrieb HamsterofDeath:
> def worksLikeThis[A, B[A] <: Traversable[A]](c: B[A]) = c.filter(e => true)
>
> Am 09.02.2012 17:55, schrieb Ka Ter:
>> Hi,
>>
>> why is the following code producing the compiler error 'type mismatch;
>> found : Traversable[Any] required: C'? The type of the collection
>> doesn't change and therefore it is a C. If I ommit the ':C' of the
>> method than the return type is inferred to Traversable[Any].
>>
>> class Test[C <: Traversable[Any] : Manifest](collection: C)
>> {
>> def test(): C = collection.filter(e => e == e)
>> }
>>
>> (new Test(Set[String]())).test
>>
>
Best RegardsEdmondo Porcu
2012/2/9 Ka Ter <ter.ka966@googlemail.com>