2

I have a case class with a companion object. I have implicit conversion method inside the companion object.

case class Foo(p:T)

object Foo {
  implicit def Foo2Bar(foo: Foo): Bar = new Bar(doSmth(foo.p))
}

I have a method with a param of type Object. I want to pass an instance of Bar there. Unfortunatelly, the following code doesn't do the conversion but throws ClassCastException:

import Foo._
...
val foo = createFoo()
bazz(foo.asInstanceOf[Bar])

At the same time, the next (more verbose) code do the job:

import Foo._
...
val foo = createFoo()
val bar: Bar = foo 
bazz(bar)

Any ideas why the former code doesn't work?

Roman
  • 64,384
  • 92
  • 238
  • 332
  • http://stackoverflow.com/questions/3412068/what-are-the-differences-between-asinstanceoft-and-o-t-in-scala – Jean Logeart Jul 25 '14 at 14:39
  • 1
    You can just use `bazz(foo: Bar)`. This will trigger the implicit conversion. Note that if `bazz` expects a `Bar` anyway, then `bazz(foo)` is enough as well. – sjrd Jul 25 '14 at 15:29

1 Answers1

3

asInstanceOf deals only with subtype relationships, but defining an implicit conversion doesn't create a subtype relationship.