Tilde in Scala found in Scalatra example code - scala

Just ran into this sample code learning about Commands in Scalatra:
protected def handle: Handler = {
case c: CreateTodoCommand =>
add(newTodo(~c.name.value))
}
In this particular case, what exactly is the relevance of ~ in ~c.name.value? Not sure where to find more documentation on this particular symbol.

In Scala:
~x
translates to
x.unary_~
(this also applies to +,- and ! as explained in this post). So your example translates to:
add(newTodo(c.name.value.unary_~))
The documentation can hence be found at the type of value.

it seems to be related to the block of code commented out in here: https://github.com/scalatra/scalatra/blob/2.2.x_2.9/core/src/main/scala/org/scalatra/package.scala
that is the only unary tilde operator if found that could be working here. the others seem to mainly be bitwise not operators
It actually seems that this might also be some import from scalaz library, tho the import statements are missing. similar uses of ~Option[_] can be found elsewhere as well...

Related

Logging syntax for Play Framework 2 in Scala

This is a really silly question, but how can you do convenient formatting of log strings in Play Framework 2 (and in Scala?).
I've googled but its very difficult to find an example, essentially most links are talking about configuring Logback in the first place which I've done fine.
I'm basically trying to find the best stylistic way to do something like:
if(Logger.isDebugEnabled)
Logger.debug("Modified: Id = '" + real_session_id + "', Modified = " + modified.toString)
Coming from a C# background (and log4net) I'd assume you could do something like:
if(Logger.isDebugEnabled)
Logger.debug("Modified: Id = '{0}', Modified = {1}", real_session_id, modified.toString)
But I can't see how this would work with the trait the way it is defined. I've also seen vague references to how you might be able to avoid checking Logger.isDebugEnabled by using a lazy evaluative syntax like:
Logger.debug("Modified: Id = ${real_session_id}, Modified = ${modified.toString}")
That uses Scala macros - but again, that doesn't work and I can find very little information about it.
Am I missing something really blatant here?
The framework used for logging is logback. When you type : Logger.debug, the isDebugEnabled is already implicitly checked.
For the syntax of logging, use the Scala string interpolation.
Logger.debug(s"Modified: Id = '$real_session_id', Modified = $modified.toString")
Why not just use the standard String interpolation capabilities of the language/stdlib? http://docs.scala-lang.org/overviews/core/string-interpolation.html
I apologise if I've missed something crucial about your question.
As to avoiding the if (Logger.isDebugEnabled) check, if the logging framework is not providing some sort of lazy evaluation scheme for arguments passed into it, I would just first consider defining my own wrappers:
object MyLazyLogger {
def debug(msg: => Any) =
if (Logger.isDebugEnabled) Logger.debug(msg)
}
Also, I don't think the way in which you interpolate stuff into the string has anything to do with not evaluating the arguments to debug() if logging is disabled—if debug() declares that it eager-evaluates any arguments passed into it, there's no way that I can see you can change to lazy evaluation at the call site by just using a "special form" of string interpolation. (I'd be happy if anyone proved me wrong here and taught me something new :))
Disclosure: I'm not familiar with Play (yet), so I'm just taking a shot at a general approach here.

Motivation for match expression syntax

The syntax for match expressions is pretty nice:
expr match {
case Test(l1) => ...
...
}
But it's driving me nuts that I don't understand the motivation to why this this syntax is used instead of match (expr) ..., like branching statements in a decent C descendant!
I see no reasonably explanation for this. And I don't find the answer neither in Programming in Scala, the Scala web site, in this paper, this thesis, here on SO nor on the rest of the web.
It's not that it's anything wrong with it, just that it's a complete mystery. And when match work in this way, why not if and for also?
Does anybody know? I don't think I can stand using the language any longer without finding this out. I think about it all the time. I can hardly sleep at night.
To take a similar bit of Scala syntax, guards in pattern matching cases don't require parentheses around their conditional expressions—e.g., the following:
case i if i % 2 == 0 => i / 2
Is just as valid as this:
case i if (i % 2 == 0) => i / 2
Sticking to the C-family style would mean requiring the latter form, even though the parentheses aren't necessary for disambiguation. The Scala language designers decided that reducing line noise trumped maintaining the family resemblance in this case.
I'd guess that a similar motivation is at work in the match syntax, and to my eye match (expr) { ... } does indeed look pretty awful (and misleading) compared to expr match { ... }.
Also, just this afternoon I refactored someone else's x match { ... } on an Option to x map { ... } instead. match as an infix operator makes the similarity between these two expressions clear.
On the issue of why match isn't just a method, here's a five year-old question from David Pollak on the scala-debate mailing list:
Why is 'match' a language level construct rather than a method on Any?
And Martin Odersky's answer:
It used to be that way in Scala 1. I am no longer sure why we changed.
syntax highlighting? error reporting? not sure. I don't think it
matters much either way, though.
I'm with Martin on this one.
Note that there are a couple of practical differences (apart from the simple "dot or not" question). For example, this doesn't compile:
def foo[A, B](f: PartialFunction[A, B])(a: A) = a match f
If match were still a method on Any, requiring a literal bunch of cases would be a rather strange requirement.

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.

Scala pattern matching syntax

I've been playing with scala pattern matching recently and was wondering whether there is a way to create an extractor inside of the case statement. The following code works, but you have to define the extractor first and assign it to a val:
val Extr = "(.*)".r
"test" match {
case Extr(str) => println(str)
}
What I would like to do, or what I would like someone to confirm is impossible, is something like this:
"test" match {
case ("(.*)".r)(str) => println(str)
}
EDIT: In case anyone from the scala team is reading this: Would it be feasible to implement this?
Unfortunately it is not possible and I see no way to simplify your first example.
The case statement has to be followed by a Pattern. The Scala Language Specification shows the BNF of patterns in section 8.1. The grammar of patterns is quite powerful, but is really just a pattern, no method calls or constructors are allowed there.
I had a similar problem and i solved it like this:
case x if x.matches("regex") => foo(x)
I don't know if this is exactly what you want, but it works

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