Scala manifest and instances - scala

I'm using Jerkson, and I need to check if a given class can be serialized. The java version just needs a class, but jerkson does this:
def canSerialize[A](implicit mf: Manifest[A]) = mapper.canSerialize(mf.erasure)
Given that I have an instance, how can I call this? I pretty much tried
canSerialize[ClassManifest.fromClass(foo)]
But its not working. I wonder why the guys at jerkson could not make it simpler by just making this: canSerialize(Class[_]) ...
Any ideas on how can I invoke this?
Edit:
I fixed this by using:
canSerilialize(Manifest.classType(foo.getClass))

How about this:
canSerialize[Foo]
Compiler can automatically generate manifest for you (if it has enough type information in context)
Since Scala 2.8.0 canSerialize can be written via context bound. See more

If you don't know the class in advance, you can always pass the manifest as a parameter, i.e. this should work: canSerialize( Manifest.classType( foo.getClass ) ).

Related

Meaning of symbol :+: in Scala?

What does the symbol :+: mean in Scala Programming language?
object Devices {
private[endpoints] def endpoints(myService: MyService[Future], pService: PService[Future]) =
"devices" / (
banDevice(myService, pService) :+:
unbanDevice(myService, pService)
)
This is the code snippet. I'm using finagle library.
I've read that scala can have function names as symbols. Is this an example of that?
Where do I find the defention of this finagle defined methods?
Is it possible to override these methods?
Scala Does not have this function , it can be inside one of the libraries that you are using. According to your code , you might be using finagle !
Hence What Peter Neyens pointed out : https://github.com/finagle/finch/blob/master/docs/endpoint.md#coproduct-endpoints.
Seems to explain what you are trying to find out.
P.s: Its just a method in one of the libraries and nothing else.
In answer to your updated questions:
Yes, that code is calling the function (actually a method) named :+:.
You can probably find the API published online (maybe here).
If the class is not sealed and the method is not final then, yes, you should be able to override it.

What does the "extends {..}" clause in Scala object definition, without superclass name, do?

I found this code example in Programming in Scala, 2nd Ed. (Chapter 25, Listing 25.11):
object PrefixMap extends {
def empty[T] = ...
def apply[T](kvs: (String, T)*): PrefixMap[T] = ...
...
}
Why is the extends clause there without a superclass name? It looks like extending an anonymous class, but for what purpose? The accompanying text doesn't explain or even mention this construct anywhere. The code actually compiles and apparently works perfectly with or without it.
OTOH I found the exact same code on several web pages, including this (which looks like the original version of the chapter in the book). I doubt that a typo could have passed below the radars of so many readers up to now... so am I missing something?
I tried to google it, but struggled even to find proper search terms for it. So could someone explain whether this construct has a name and/or practical use in Scala?
Looks like a print error to me. It will work all the same, though, which probably helped hide it all this time.
Anyway, that object is extending a structural type, though it could also be an early initialization, if you had with XXX at the end. MMmmm. It looks more like an early initialization without any class or trait to be initialized later, actually... structure types do not contain code, I think.

How to get the class of a singleton object at compile time?

Consider something like this:
object Singleton
val cls: Class[Singleton] = ???
What do I have to write instead of ????
I tried classOf[Singleton], classOf[Singleton.type], Singleton.type, but nothing worked.
(I know of course about getClass, the runtime version of classOf, but that's not what I'm asking.)
Here a solution, but it's not pretty ...
object Singleton
val cls : Class[Singleton] = Singleton.getClass.asInstanceOf[Class[Singleton]]
Edit: completed the solution after reading another question/answer: Scala equivalent of Java java.lang.Class<T> Object
Note1: type erasure would prevent this from being particularly useful, e.g. in pattern matching. See referenced question/answer, above, for a good explanation
Note2: the scala -explaintypes flag is quite handy in understanding type errors.
HTH
You are not alone with this problem. The answer is: There is currently no way to avoid a Singleton.getClass. See this comment for more information why classOf[Singleton] does not work

automatic xml conversion in scala

Let's say I have the following class:
class Person(val firstName:String, val lastName:String)
Is there an automatic way to generate xml from this class without having to hand create a toXml() method? Ideally the output would be something like:
<Person>
<firstName>John</firstName>
<lastName>Smith</lastName>
</Person>
It seems like there should be a way to do this without having to write all that out manually. Perhaps there is a trait I haven't found yet?
For case classes (or other subclasses of Product), this was once very easy to write generically: the name can be retrieved with productPrefix, all values are iterable via productIterator and the names of the fields via productElementName.
Unfortunately, productElementName has only had a very short life: it was added in revision 20958 and removed in revision 21223, apparently because it added too much weight to case classes (there's also an open ticket for it).
Unfortunately, I don't think there is such a magic trait. You could use something like XStream to accomplish this. However, it doesn't seem print all Scala classes that pretty automatically, so you probably need to write your own converter. Someone else has already done so in the case of Lists, I guess for your example you might need something similar.

Does Scala have introspection capable of something similar to Python's dir()?

Yes, I know it's considered lazy by the non-Pythonistas. The reason I ask is that documentation is still woefully lacking in many Scala libraries (e.g. Scala-dbc, but that's not all I'm looking at), and if I could see the attributes of an object/class at runtime, I could at least figure out what's available. Thanks.
Scala does not have a reflection API. The only way to access this information is to use the Java reflection API. This has the disadvantage that the structure may change as the way Scala is represented in Java classes and interfaces may change in the future.
scala> classOf[AnyRef].getMethods
res0: Array[java.lang.reflect.Method] = Array(public final void ...
Some specific type information that is present in the byte code can be accessed with the ScalaSigParser.
import tools.scalap.scalax.rules.scalasig._
import scala.runtime._
val scalaSig = ScalaSigParser.parse(classOf[RichDouble])
That's one of my main uses for REPL. Type the object's name, dot, and then TAB and it will show all available methods.
It isn't perfect. For one thing, it shows protected methods, which won't be available unless you are extending the class. For another thing, it doesn't show methods available through implicit conversion.
And, of course, the IDEs are all capable of doing that.
You might want something like the following which would give you what you need. In this case, it operates on a String, obviously.
val testStr = "Panda"
testStr.getClass.getMethods.foreach(println)
Does that work?
You may want to use this little helper to beef up the REPL