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

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.

Related

this: SomeObject => object construct

I was reading up on best practices for implementing Slick, and was examining this example. In it, there is this construct:
trait BankRepository extends BankTable { this: DBComponent =>
... //A bunch of code
}
I don't understand the this: DBComponent => part. In this case, DBComponent is a simple trait defined elsewhere (you can find it in the above link). What I don't understand is:
What does the this: DBComponent => construct do. My IDE doesn't complain, but it also doesn't link to the function being executed by the =>. My intuition is that it's saying the rest of the code is a value that is returned, but I'm not clear on what is invoking it, or what the value returned exactly.
What do I even call this construct? As with many symbol-heavy constructs it's hard to look up/find documentation of, because it's clearly dependent on context. But even describing the context is difficult. What is this construct called?
It's called a self type. It's basically a contract that says any class extending this trait (mixing it in) must include DBComponent. And, as such, the compiler should assume DBCompenent elements are in scope for the following code.
Here's a link to a description of it from Programming in Scala, Odersky et al, 1st Edition (a little dated but still accurate on most topics).

Is it possible to achieve functionality provided by implicit classes via macros?

We are pretty familiar with implicits in Scala for now, but macros are pretty undiscovered area (at least for me) and, despite the presence of some great articles by Eugene Burmako, it is still not an easy material to just dive in.
In this particular question I'd like to find out if there is a possibility to achieve the analogous to the following code functionality using just macros:
implicit class Nonsense(val s: String) {
def ##(i:Int) = s.charAt(i)
}
So "asd" ## 0 will return 'a', for example. Can I implement macros that use infix notation? The reason to this is I'm writing a DSL for some already existing project and implicits allow making the API clear and concise, but whenever I write a new implicit class, I feel like introducing a new speed-reducing factor. And yes, I do know about value classes and stuff, I just think it would be really great if my DSL transformed into the underlying library API calls during compilation rather than in runtime.
TL;DR: can I replace implicits with macros while not changing the API? Can I write macros in infix form? Is there something even more suitable for this case? Is the trouble worth it?
UPD. To those advocating the value classes: in my case I have a little more than just a simple wrapper - they are often stacked. For example, I have an implicit class that takes some parameters, returns a lambda wrapping this parameters (i.e. partial function), and the second implicit class that is made specifically for wrapping this type of functions. I can achieve something like this:
a --> x ==> b
where first class wraps a and adds --> method, and the second one wraps the return type of a --> x and defines ==>(b). Plus it may really be the case when user creates considerable amount of objects in this fashion. I just don't know if this will be efficient, so if you could tell me that value classes cover this case - I'd be really glad to know that.
Back in the day (2.10.0-RC1) I had trouble using implicit classes for macros (sorry, I don't recollect why exactly) but the solution was to use:
an implicit def macro to convert to a class
define the infix operator as a def macro in that class
So something like the following might work for you:
implicit def toNonsense(s:String): Nonsense = macro ...
...
class Nonsense(...){
...
def ##(...):... = macro ...
...
}
That was pretty painful to implement. That being said, macro have become easier to implement since.
If you want to check what I did, because I'm not sure that applies to what you want to do, refer to this excerpt of my code (non-idiomatic style).
I won't address the relevance of that here, as it's been commented by others.

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

In Scala is there any way to get a parameter's method name and class?

At my work we use a typical heavy enterprise stack of Hibernate, Spring, and JSF to handle our application, but after learning Scala I've wanted to try to replicate much of our functionality within a more minimal Scala stack (Squeryl, Scalatra, Scalate) to see if I can decrease code and improve performance (an Achilles heal for us right now).
Often my way of doing things is influenced by our previous stack, so I'm open to advice on a way of doing things that are closer to Scala paradigms. However, I've chosen some of what I do based on previous paradigms we have in the Java code base so that other team members will hopefully be more receptive to the work I'm doing. But here is my question:
We have a domain class like so:
class Person(var firstName: String, var lastName: String)
Within a jade template I make a call like:
.section
- view(fields)
The backing class has a list of fields like so:
class PersonBean(val person: Person) {
val fields: Fields = Fields(person,
List(
Text(person.firstName),
Text(person.lastName)
))
}
Fields has a base object (person) and a list of Field objects. Its template prints all its fields templates. Text extends Field and its Jade template is supposed to print:
<label for="person:firstName">#{label}</label>: <input type="text" id="person:firstName" value="#{value}" />
Now the #{value} is simply a call to person.firstName. However, to find out the label I reference a ResourceBundle and need to produce a string key. I was thinking of using a naming convention like:
person.firstName.field=First Name
So the problem then becomes, how can I within the Text class (or parent Field class) discover what the parameter being passed in is? Is there a way I can pass in person.firstName and find that it is calling firstName on class Person? And finally, am I going about this completely wrong?
If you want to take a walk on the wild side, there's a (hidden) API in Scala that allows you to grab the syntax tree for a thunk of code - at runtime.
This incantation goes something like:
scala.reflect.Code.lift(f).tree
This should contain all the information you need, and then some, but you'll have your work cut out interpreting the output.
You can also read a bit more on the subject here: Can I get AST from live scala code?
Be warned though... It's rightly classified as experimental, do this at your own risk!
You can never do this anywhere from within Java, so I'm not wholly clear as to how you are just following the idiom you are used to. The obvious reason that this is not possible is that Java is pass-by-value. So in:
public void foo(String s) { ... }
There is no sense that the parameter s is anything other than what it is. It is not person.firstName just because you called foo like:
foo(person.firstName);
Because person.firstName and s are completely separate references!
What you could do is replacing the fields (e.g. firstname) with actual objects, which have a name attribute.
I did something similiar in a recent blog post:http://blog.schauderhaft.de/2011/05/01/binding-scala-objects-to-swing-components/
The property doesn't have a name property (yet), but it is a full object but is still just as easy to use as a field.
I would not be very surprised if the following is complete nonsense:
Make the parameter type of type A that gets passed in not A but Context[A]
create an implicit that turns any A into a Context[A] and while doing so captures the value of the parameter in a call-by-name parameter
then use reflection to inspect the call-by-name parameter that gets passed in
For this to work, you'd need very specific knowledge of how stuff gets turned into call-by-name functions; and how to extract the information you want (if it's present at all).

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