In general, you should avoid structural typing, as it is very expensive. The call will be converted to a reflection call due to restrictions in the JVM. When you start using scala 2.10, structural types will cause a warning at compile time (although you can disable this with a flag).
If you are learning a more general way of adding functionality to classes that donβt share the inheritance hierarchy, you can use type classes.
Here is an example:
trait CanCreateRFromA[A,R]{ def createNew(a:A): R } implicit object CanCreateBlahFromInt extends CanCreateRFromA[Int,Blah2]{ def createNew(i:Int):Blah2 = new Blah2(i) } implicit object CanCreateBlah1FromString extends CanCreateRFromA[String,Blah1]{ def createNew(s:String):Blah1 = new Blah1(s) } case class Blah1(something:String) case class Blah2(something:Int) def createRFromA[A,R](a:A)(implicit tc:CanCreateRFromA[A,R])= tc.createNew(a)
Then you can call:
createRFromA(1)
Again, I'm not sure what you are trying to accomplish, but maybe you can do what you want with a type class, and that will be much faster.
source share