This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Re: Question about wild card in try catch case statement

No replies
scala
Joined: 2009-02-12,
User offline. Last seen 42 years 45 weeks ago.
Thanks Guys,

This does clarifies lot of my doubts about using _ in types and in expression.

-daya

On Thu, Feb 12, 2009 at 7:58 PM, Matt Hellige (matt [at] immute [dot] net) wrote:
>
> On Thu, Feb 12, 2009 at 11:48 AM, <scala [at] daya [dot] otherinbox [dot] com> wrote:
> > Hi All,
> >
> > I am wondering why the code below doesn't compile
> >
> > scala:258> def some = {try {println("something")}catch{case e: _ =>
> > e.printStackTrace}}
> > :1: error: unbound wildcard type
> > def some = {try {println("something")}catch{case e: _ =>
> > e.printStackTrace}}
> >
> > specially if I want to use _ as a wild card to catch exceptions of all
> > types.
> >
> > I understand that I can do
> >
> > scala:254> def some = {try {println("something")}catch{case e:Throwable =>
> > e.printStackTrace}}
> > some: Unit
> >
> > or even this
> >
> > scala:265> def some = {try {println("something")}catch{case e =>
> > e.printStackTrace}}
> > some: Unit
> >
> > but that is not the point ... and I would like to know why _ wild card can't
> > be used instead ??
>
> Because _ in types is different from _ in expressions. In a type, _ is
> a shorter form of an existential type: Foo[_] means Foo[A] forSome {
> type A }. Moreover, the language reference says "A wildcard type must
> appear as type argument of a parameterized type," (p. 25) which
> explains your type error. But if it were allowed, your pattern would
> be equivalent to "case e: A forSome { type A }", which (according to p
> 24) is the same as "case e: Any".
>
> The short answer is: _ doesn't mean what you think it means. Use Any
> instead in such cases, or (even better) just leave off the type
> annotation. In a pattern, why do you want to write the annotation at
> all?
>
> Matt
>

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland