- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
wildcard trouble
Thu, 2012-01-26, 21:37
hi,
why does this not compile?
object WildCard {
class Other[T2] {
}
class Param[T] {
def getOther = new Other[T]
def takeItBack(other:Other[T]) {
println("works like a charm")
}
}
def doesNotCompile(param:Param[_]) {
val other = param.getOther
param.takeItBack(other)
}
}
to me, it is totally obvious that "other" has the correct type. the compiler doesn't think so. how can i convince it?
i cannot simply use a type parameter because want this to work:
def traverse(coll:Traversable[Param[_]]) {
val head = coll.head
val other = head.getOther
head.takeItBack(other)
}
and the different elements of coll have different type parameters which cannot be expressed using a single type parameter, hence the wildcard.
is it possible to tell the compiler that the actual type is unknown, but that both unknown types are equal?
Thu, 2012-01-26, 23:01
#2
Re: wildcard trouble
any idea why the compiler can not figure this out on its own?
-------- Original-Nachricht --------
> Datum: Thu, 26 Jan 2012 12:51:24 -0800
> Von: Christopher
> An: Dennis Haupt
> CC: scala-user@googlegroups.com
> Betreff: Re: [scala-user] wildcard trouble
> Turn "doesNotCompile" into a generic method, and call it from "traverse":
>
> scala> object WildCard {
> | class Other[T2] {}
> | class Param[T] { def getOther = new Other[T]; def takeItBack(other:
> Other[T]) { println("works like a charm"); } }
> | def doesNotCompile[X](param: Param[X]) {
> | val other = param.getOther
> | param.takeItBack(other)
> | }
> | def traverse(coll: Traversable[Param[_]]) {
> | val head = coll.head
> | doesNotCompile(head)
> | }
> | }
> defined module WildCard
>
>
> scala> WildCard.traverse(List(new WildCard.Param[Int], new
> WildCard.Param[Boolean]))
> works like a charm
>
>
>
>
>
Fri, 2012-01-27, 00:41
#3
Re: wildcard trouble
On Thu, Jan 26, 2012 at 1:53 PM, Dennis Haupt wrote:
> any idea why the compiler can not figure this out on its own?
Unfortunately, I have not spent the requisite amount of time studying
type inference algorithms to have a clue. I imagine it's "hard," where
"hard" is defined as either, "the kind of type inference Scala uses
doesn't do this well," or "no one has devoted the man hours to solve a
problem with an existing alternative solution."
CC
scala> object WildCard { | class Other[T2] {} | class Param[T] { def getOther = new Other[T]; def takeItBack(other: Other[T]) { println("works like a charm"); } } | def doesNotCompile[X](param: Param[X]) { | val other = param.getOther | param.takeItBack(other) | } | def traverse(coll: Traversable[Param[_]]) { | val head = coll.head | doesNotCompile(head) | } | }defined module WildCard
scala> WildCard.traverse(List(new WildCard.Param[Int], new WildCard.Param[Boolean]))works like a charm
--
Christopher
Sent with Sparrow
On Thursday, January 26, 2012 at 12:37 PM, Dennis Haupt wrote: