Automatic conversion to Object

38 views
Skip to first unread message

Marek Broda

unread,
Aug 3, 2012, 9:07:18 PM8/3/12
to scala...@googlegroups.com
Hello everyone,

I have a problem with converting scala types to object. Consider following code:

def doSomeStuff[A](x: A) = {
    val o: Object = x
}
   
this won't work as Object is a java reference type and A is Any and could by a primitive type. I know it could be solved by putting a view or inheritance constraint on A, but then i would have to repeat this constraint for every generic method that uses this method, and for every generic class that uses this method. Is there way to avoid this, some way to automatically box scala Any value?

Regards,
Marek Broda

Seth Tisue

unread,
Aug 6, 2012, 8:53:47 AM8/6/12
to scala...@googlegroups.com
On Fri, Aug 3, 2012 at 9:07 PM, Marek Broda <broda...@gmail.com> wrote:
> Is there [...] some way to automatically box scala
> Any value?

x.asInstanceOf[AnyRef]

Idea: Scala has `box` methods on the companion objects for all the
specific AnyVal types (Int.box, Double.box, and so on) it, so it would
be nice if the standard library provided `Any.box` as well, as a
shorter way of writing the above.

Why add a method that doesn't add a new capability? Because normally
the presence of `asInstanceOf` means you're doing an end run around
the type system. But boxing an Any is perfectly typesafe, so Scala
ought not to force me to drop down to asInstanceOf, IMO.

--
Seth Tisue | Northwestern University | http://tisue.net
lead developer, NetLogo: http://ccl.northwestern.edu/netlogo/
Reply all
Reply to author
Forward
0 new messages