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

How to do Casting ?

4 replies
Steven Obua
Joined: 2009-03-25,
User offline. Last seen 42 years 45 weeks ago.

Hi,

in the code below I try to cast a value "MyConstr" to type "MyClass".
Running the code throws a ClassCastException. What am I doing wrong?

Thanks,

Steven


package ra

object Main {

class MyClass
case class MyConstr extends MyClass

def main(args: Array[String]) = {
val e = MyConstr
val f = e.asInstanceOf[MyClass]
println("hello")
}

}

Carsten Saager
Joined: 2008-12-19,
User offline. Last seen 42 years 45 weeks ago.
Re: How to do Casting ?
try

val e = MyConstr()

- Carsten

On Thu, Apr 2, 2009 at 4:40 PM, Steven Obua <obua@me.com> wrote:

Hi,

in the code below I try to cast a value "MyConstr" to type "MyClass".
Running the code throws a ClassCastException. What am I doing wrong?

Thanks,

Steven

<code>
package ra

object Main {

 class MyClass
 case class MyConstr extends MyClass

 def main(args: Array[String]) = {
   val e = MyConstr
   val f = e.asInstanceOf[MyClass]
   println("hello")
 }

}
</code>
--
View this message in context: http://www.nabble.com/How-to-do-Casting---tp22849464p22849464.html
Sent from the Scala mailing list archive at Nabble.com.


Steven Obua
Joined: 2009-03-25,
User offline. Last seen 42 years 45 weeks ago.
Re: How to do Casting ?

Ok, found my mistake.

I think I confused "MyConstr" with "MyConstr ()".

Steven

ijuma
Joined: 2008-08-20,
User offline. Last seen 22 weeks 2 days ago.
Re: Re: How to do Casting ?

On Thu, 2009-04-02 at 08:04 -0700, Steven Obua wrote:
> Ok, found my mistake.
>
> I think I confused "MyConstr" with "MyConstr ()".

Note that case classes without a parameter lists have been deprecated.
As the compiler suggests, use case objects or case classes with () as
the parameter list.

Ismael

Ricky Clarkson
Joined: 2008-12-19,
User offline. Last seen 3 years 2 weeks ago.
Re: How to do Casting ?
MyConstr refers to a singleton; the generated companion object MyClass.
Generally, if in doubt, add type annotations.
val e: MyConstr = MyConstr //will fail to compile, telling you the problem.

2009/4/2 Carsten Saager <csaager@gmail.com>
try

val e = MyConstr()

- Carsten

On Thu, Apr 2, 2009 at 4:40 PM, Steven Obua <obua@me.com> wrote:

Hi,

in the code below I try to cast a value "MyConstr" to type "MyClass".
Running the code throws a ClassCastException. What am I doing wrong?

Thanks,

Steven

<code>
package ra

object Main {

 class MyClass
 case class MyConstr extends MyClass

 def main(args: Array[String]) = {
   val e = MyConstr
   val f = e.asInstanceOf[MyClass]
   println("hello")
 }

}
</code>
--
View this message in context: http://www.nabble.com/How-to-do-Casting---tp22849464p22849464.html
Sent from the Scala mailing list archive at Nabble.com.



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