Use of option helper in Play Framework 2.0 templates - scala

I'm trying to use views.html.helper.select (documentation here). I don't know scala, so i'm using java. I need to pass object of type Seq[(String)(String)] to the template right? Something like:
#(fooForm:Form[Foo])(optionValues:Seq[(String)(String)])
#import helper._
#form(routes.foo){
#select(field=myForm("selectField"),options=optionValues)
}
I don't know how to create Seq[(String)(String)] in java. I need to fill this collection with pairs (id,title) from my enum class.
Can somebody show me some expample how to use the select helper?
I found this thread on users group, but Kevin's answer didn't helped me a lot.

The right type is: Seq[(String, String)]. It means a sequence of pairs of String. In Scala there is a way to define pairs using the arrow: a->b == (a, b). So you could write e.g.:
#select(field = myForm("selectField"), options = Seq("foo"->"Foo", "bar"->"Bar"))
But there is another helper, as shown in the documentation, to build the sequence of select options: options, so you can rewrite the above code as:
#select(myForm("selectField"), options("foo"->"Foo", "bar"->"Bar"))
In the case your options values are the same as their label, you can even shorten the code to:
#select(myForm("selectField"), options(List("Foo", "Bar")))
(note: in Play 2.0.4 options(List("Foo", "Bar")) doesn't compile, so you can try this options(Seq("Foo", "Bar")))
To fill the options from Java code, the more convenient way is to use either the overloaded options function taking a java.util.List<String> as parameter (in this cases options values will be the same as their label) or the overloaded function taking a java.util.Map<String, String>.

Related

apply method on Map object?

First of all let me apologize in advance for what is my very first question posted on stack overflow and probably a quite stupid one.
Since a Map in scala is instantiated using the following syntax:
val myMap=Map(1->”value1”,2->”value2”)
I was expecting the Map object from scala.collection.immutable to provide an apply method with a signature roughly looking like:
def apply[A,B](entries :(A,B)*):Map[A,B]
Obviously I should be blind, but I can’t find such a method. Where is it defined ?
Furthermore, could someone give me information about the purpose of the Map1, Map2, Map3, Map4 classes defined in the Map object ? Should they be used by the developer or are they only used internally by the language and/or the compiler ? Are they related somehow to the map instantiation scheme i was asking about above ?
Thanks in advance for your help.
apply looks like it is defined on scala.collection.generic.GenMapFactory, a superclass of scala.collection.immutable.Map. For some reason, Scaladoc simply ignores this method for 2.9.2. (As Rogach notes, it was there in 2.9.1.)
Map1…Map4 (together with EmptyMap, which is private) are simply optimisations. These are defined inside Map.scala and really just hold up to four keys and values directly without any further indirection. If one tries to add to a Map4, a HashMap will automatically be created.
You normally do not need to create a Map[1-4] manually:
scala> Map('a -> 1)
res0: scala.collection.immutable.Map[Symbol,Int] = Map('a -> 1)
scala> res0.isInstanceOf[scala.collection.immutable.Map.Map1[_,_]]
res1: Boolean = true

Scala Case Class Map Expansion

In groovy one can do:
class Foo {
Integer a,b
}
Map map = [a:1,b:2]
def foo = new Foo(map) // map expanded, object created
I understand that Scala is not in any sense of the word, Groovy, but am wondering if map expansion in this context is supported
Simplistically, I tried and failed with:
case class Foo(a:Int, b:Int)
val map = Map("a"-> 1, "b"-> 2)
Foo(map: _*) // no dice, always applied to first property
A related thread that shows possible solutions to the problem.
Now, from what I've been able to dig up, as of Scala 2.9.1 at least, reflection in regard to case classes is basically a no-op. The net effect then appears to be that one is forced into some form of manual object creation, which, given the power of Scala, is somewhat ironic.
I should mention that the use case involves the servlet request parameters map. Specifically, using Lift, Play, Spray, Scalatra, etc., I would like to take the sanitized params map (filtered via routing layer) and bind it to a target case class instance without needing to manually create the object, nor specify its types. This would require "reliable" reflection and implicits like "str2Date" to handle type conversion errors.
Perhaps in 2.10 with the new reflection library, implementing the above will be cake. Only 2 months into Scala, so just scratching the surface; I do not see any straightforward way to pull this off right now (for seasoned Scala developers, maybe doable)
Well, the good news is that Scala's Product interface, implemented by all case classes, actually doesn't make this very hard to do. I'm the author of a Scala serialization library called Salat that supplies some utilities for using pickled Scala signatures to get typed field information
https://github.com/novus/salat - check out some of the utilities in the salat-util package.
Actually, I think this is something that Salat should do - what a good idea.
Re: D.C. Sobral's point about the impossibility of verifying params at compile time - point taken, but in practice this should work at runtime just like deserializing anything else with no guarantees about structure, like JSON or a Mongo DBObject. Also, Salat has utilities to leverage default args where supplied.
This is not possible, because it is impossible to verify at compile time that all parameters were passed in that map.

Examples of using some Scala Option methods

I have read the blog post recommended me here. Now I wonder what some those methods are useful for. Can you show examples of using forall (as opposed to foreach) and toList of Option?
map: Allows you to transform a value "inside" an Option, as you probably already know for Lists. This operation makes Option a functor (you can say "endofunctor" if you want to scare your colleagues)
flatMap: Option is actually a monad, and flatMap makes it one (together with something like a constuctor for a single value). This method can be used if you have a function which turns a value into an Option, but the value you have is already "wrapped" in an Option, so flatMap saves you the unwrapping before applying the function. E.g. if you have an Option[Map[K,V]], you can write mapOption.flatMap(_.get(key)). If you would use a simple map here, you would get an Option[Option[V]], but with flatMap you get an Option[V]. This method is cooler than you might think, as it allows to chain functions together in a very flexible way (which is one reason why Haskell loves monads).
flatten: If you have a value of type Option[Option[T]], flatten turns it into an Option[T]. It is the same as flatMap(identity(_)).
orElse: If you have several alternatives wrapped in Options, and you want the first one that holds actually a value, you can chain these alternatives with orElse: steakOption.orElse(hamburgerOption).orElse(saladOption)
getOrElse: Get the value out of the Option, but specify a default value if it is empty, e.g. nameOption.getOrElse("unknown").
foreach: Do something with the value inside, if it exists.
isDefined, isEmpty: Determine if this Option holds a value.
forall, exists: Tests if a given predicate holds for the value. forall is the same as option.map(test(_)).getOrElse(true), exists is the same, just with false as default.
toList: Surprise, it converts the Option to a List.
Many of the methods on Option may be there more for the sake of uniformity (with collections) rather than for their usefulness, as they are all very small functions and so do not spare much effort, yet they serve a purpose, and their meanings are clear once you are familiar with the collection framework (as is often said, Option is like a list which cannot have more than one element).
forall checks a property of the value inside an option. If there is no value, the check pass. For example, if in a car rental, you are allowed one additionalDriver: Option[Person], you can do
additionalDriver.forall(_.hasDrivingLicense)
exactly the same thing that you would do if several additional drivers were allowed and you had a list.
toList may be a useful conversion. Suppose you have options: List[Option[T]], and you want to get a List[T], with the values of all of the options that are Some. you can do
for(option <- options; value in option.toList) yield value
(or better options.flatMap(_.toList))
I have one practical example of toList method. You can find it in scaldi (my Scala dependency injection framework) in Module.scala at line 72:
https://github.com/OlegIlyenko/scaldi/blob/f3697ecaa5d6e96c5486db024efca2d3cdb04a65/src/main/scala/scaldi/Module.scala#L72
In this context getBindings method can return either Nil or List with only one element. I can retrieve it as Option with discoverBinding. I find it convenient to be able to convert Option to List (that either empty or has one element) with toList method.

SQL DSL for Scala

I am struggling to create a SQL DSL for Scala. The DSL is an extension to Querydsl, which is a popular Query abstraction layer for Java.
I am struggling now with really simple expressions like the following
user.firstName == "Bob" || user.firstName == "Ann"
As Querydsl supports already an expression model which can be used here I decided to provide conversions from Proxy objects to Querydsl expressions. In order to use the proxies I create an instance like this
import com.mysema.query.alias.Alias._
var user = alias(classOf[User])
With the following implicit conversions I can convert proxy instances and proxy property call chains into Querydsl expressions
import com.mysema.query.alias.Alias._
import com.mysema.query.types.expr._
import com.mysema.query.types.path._
object Conversions {
def not(b: EBoolean): EBoolean = b.not()
implicit def booleanPath(b: Boolean): PBoolean = $(b);
implicit def stringPath(s: String): PString = $(s);
implicit def datePath(d: java.sql.Date): PDate[java.sql.Date] = $(d);
implicit def dateTimePath(d: java.util.Date): PDateTime[java.util.Date] = $(d);
implicit def timePath(t: java.sql.Time): PTime[java.sql.Time] = $(t);
implicit def comparablePath(c: Comparable[_]): PComparable[_] = $(c);
implicit def simplePath(s: Object): PSimple[_] = $(s);
}
Now I can construct expressions like this
import com.mysema.query.alias.Alias._
import com.mysema.query.scala.Conversions._
var user = alias(classOf[User])
var predicate = (user.firstName like "Bob") or (user.firstName like "Ann")
I am struggling with the following problem.
eq and ne are already available as methods in Scala, so the conversions aren't triggered when they are used
This problem can be generalized as the following. When using method names that are already available in Scala types such as eq, ne, startsWith etc one needs to use some kind of escaping to trigger the implicit conversions.
I am considering the following
Uppercase
var predicate = (user.firstName LIKE "Bob") OR (user.firstName LIKE "Ann")
This is for example the approach in Circumflex ORM, a very powerful ORM framework for Scala with similar DSL aims. But this approach would be inconsistent with the query keywords (select, from, where etc), which are lowercase in Querydsl.
Some prefix
var predicate = (user.firstName :like "Bob") :or (user.firstName :like "Ann")
The context of the predicate usage is something like this
var user = alias(classOf[User])
query().from(user)
.where(
(user.firstName like "Bob") or (user.firstName like "Ann"))
.orderBy(user.firstName asc)
.list(user);
Do you see better options or a different approach for SQL DSL construction for Scala?
So the question basically boils down to two cases
Is it possible to trigger an implicit type conversion when using a method that exists in the super class (e.g. eq)
If it is not possible, what would be the most Scalaesque syntax to use for methods like eq, ne.
EDIT
We got Scala support in Querydsl working by using alias instances and a $-prefix based escape syntax. Here is a blog post on the results : http://blog.mysema.com/2010/09/querying-with-scala.html
There was a very good talk at Scala Days: Type-safe SQL embedded in Scala by Christoph Wulf.
See the video here: Type-safe SQL embedded in Scala by Christoph Wulf
Mr Westkämper - I was pondering this problem, and I wondered if would be possible to use 'tracer' objects, where the basic data types such as Int and String would be extended such that they contained source information, and the results of combining them would likewise hold within themselves their sources and the nature of the combination.
For example, your user.firstName method would return a TracerString, which extends String, but which also indicates that the String corresponds to a column in a relation. The == method would be overwritten such that it returns an EqualityTracerBoolean which extends Boolean. This would preserve the standard Scala semantics. However, the constructor for EqualityTracerBoolean would record the fact that the result of the expression was derived by comparing a column in a relation to a string constant. Your 'where' method could then analyse the EqualityTracerBoolean object returned by the conditional expression evaluated over a dummy argument in order to derive the expression used to create it.
There would have to be override defs for inequality operators, as well as plus and minus, for Ints, and whatever else you wished to represent from sql, and corresponding tracer classes for each of these. It would be a bit of a project!
Anyway, I decided not to bother, and use squeryl instead.
I didn't have the exact same problem with jOOQ, as I'm using a bit more verbose operator names: equal, notEqual, etc instead of eq, ne. On the other hand, there is a val operator in jOOQ for explicitly creating bind values, which I had to overload with value, as val is a keyword in Scala. Is overloading operators an option for you? I documented my attempts of running jOOQ in Scala here:
http://lukaseder.wordpress.com/2011/12/11/the-ultimate-sql-dsl-jooq-in-scala/
Just like you, I had also thought about capitalising all keywords in a major release (including SELECT, FROM, etc). But that will leave an open question about whether "compound" keywords should be split in two method calls, or connected by an underscore: GROUP().BY() or GROUP_BY(). WHEN().MATCHED().THEN().UPDATE() or WHEN_MATCHED_THEN_UPDATE(). Since the result is not really satisfying, I guess it's not worth to break backwards-compatibility for such a fix, even if the two-method-call option would look very very nice in Scala, as . and () can be omitted. So maybe, jOOQ and QueryDSL should both be "wrapped" (as opposed to "extended") by a dedicated Scala-API?
What about decompiling the bytecode at runtime? I started to write such a tool:
http://h2database.com/html/jaqu.html#natural_syntax
I know it's a hack, so please don't vote -1 :-) I just wanted to mentioned it. It's a relatively novel approach. Instead of decompiling at runtime, it might be possible to do it at compile time using an annotation processor, not sure if that's possible using Scala (and not sure if it's really possible with Java, but Project Lombok seems to do something like that).

How do I read this OCaml type signature?

I'm currently experimenting with using OCaml and GTK together (using the lablgtk bindings). However, the documentation isn't the best, and while I can work out how to use most of the features, I'm stuck with changing notebook pages (switching to a different tab).
I have found the function that I need to use, but I don't know how to use it. The documentation seems to suggest that it is in a sub-module of GtkPackProps.Notebook, but I don't know how to call this.
Also, this function has a type signature different to any I have seen before.
val switch_page : ([> `notebook ], Gpointer.boxed option -> int -> unit) GtkSignal.t
I think it returns a GtkSignal.t, but I have no idea how to pass the first parameter to the function (the whole part in brackets).
Has anyone got some sample code showing how to change the notebook page, or can perhaps give me some tips on how to do this?
What you have found is not a function but the signal. The functional type you see in its type is the type of the callback that will be called when the page switch happen, but won't cause it.
by the way the type of switch_page is read as: a signal (GtkSignal.t) raised by notebook [> `notebook ], whose callbacks have type Gpointer.boxed option -> int -> unit
Generally speaking, with lablgtk, you'd better stay away of the Gtk* low level modules, and use tge G[A-Z] higher level module. Those module API look like the C Gtk one, and I always use the main Gtk doc to help myself.
In your case you want to use the GPack.notebook object and its goto_page method.
You've found a polymorphic variant; they're described in the manual in Section 4.2, and the typing rules always break my head. I believe what the signature says is that the function switch_page expects as argument a GtkSignal.t, which is an abstraction parameterized by two types:
The first type parameter,
[> `notebook]
includes as values any polymorphic variant including notebook (that's what the greater-than means).
The second type parameter is an ordinary function.
If I'm reading the documentation for GtkSignal.t correctly, it's not a function at all; it's a record with three fields:
name is a string.
classe is a polymorphic variant which could be ``notebook` or something else.
marshaller is a marshaller for the function type Gpointer.boxed option -> int -> unit.
I hope this helps. If you have more trouble, section 4.2 of the manual, on polymorphic variants, might sort you out.