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

List of Classes of arbitrary type

5 replies
heiko.seeberger
Joined: 2008-09-16,
User offline. Last seen 1 year 28 weeks ago.

Hi,

How can I create a List of Classes of arbitrary type?
For a List[Class[AnyRef]] the compiler won't allow me to use
List(classOf[String]).

Thanx
Heiko

hseeberger
Joined: 2008-12-27,
User offline. Last seen 1 year 25 weeks ago.
List of Classes of arbitrary type

Hi,

How can I create a List of Classes of arbitrary type?
For a List[Class[AnyRef]] the compiler won't allow me to use
List(classOf[String]).

Thanx
Heiko

Roman Roelofsen
Joined: 2009-03-03,
User offline. Last seen 42 years 45 weeks ago.
Re: List of Classes of arbitrary type

Heiko Seeberger wrote:
> Hi,
>
> How can I create a List of Classes of arbitrary type?
> For a List[Class[AnyRef]] the compiler won't allow me to use
> List(classOf[String]).
>
> Thanx
> Heiko

In a perfect world, the type parameter of the 'Class' class would have
been declared to be co-variant. E.g.

class Class[+T] ...

However, the world is not perfect and this class was defined in Java,
not Scala. To deal with this, Scala has "existential types". If you
declare your list like in the snippet below it should work:

var classes = List[Class[_ <: Object]]()
classes += classOf[Object]
classes += classOf[String]

Cheers,

Roman

James Iry
Joined: 2008-08-19,
User offline. Last seen 1 year 23 weeks ago.
Re: List of Classes of arbitrary type
scala> class Foo; class Bar
defined class Foo
defined class Bar

scala> val x : List[Class[_]] = List(classOf[String], classOf[Int], classOf[Foo], classOf[Bar])
x: List[Class[_]] = List(class java.lang.String, int, class Foo, class Bar)


On Tue, Mar 3, 2009 at 12:40 PM, Heiko Seeberger <heiko.reg@seebergers.de> wrote:
Hi,

How can I create a List of Classes of arbitrary type?
For a List[Class[AnyRef]] the compiler won't allow me to use List(classOf[String]).

Thanx
Heiko


John Nilsson
Joined: 2008-12-20,
User offline. Last seen 42 years 45 weeks ago.
Re: List of Classes of arbitrary type

List[Class[+AnyRef]] ?

BR,
John

On Tue, Mar 3, 2009 at 9:44 PM, Heiko Seeberger
wrote:
> Hi,
>
> How can I create a List of Classes of arbitrary type?
> For a List[Class[AnyRef]] the compiler won't allow me to use
> List(classOf[String]).
>
> Thanx
> Heiko
>

Jorge Ortiz
Joined: 2008-12-16,
User offline. Last seen 29 weeks 4 days ago.
Re: List of Classes of arbitrary type
Try List[Class[_]]

--j

On Tue, Mar 3, 2009 at 12:44 PM, Heiko Seeberger <heiko.seeberger@googlemail.com> wrote:
Hi,

How can I create a List of Classes of arbitrary type?
For a List[Class[AnyRef]] the compiler won't allow me to use List(classOf[String]).

Thanx
Heiko

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