First, I'm sorry for asking such a dumb question, but quick googling didn't help me much...
I'm a Java delevoper and very new to Groovy. Consider the following code snippet:
class Person {
public String name
}
def jack = new Person()
jack.name = "Jack"
def bob = new Person()
bob.name = "Bob"
def list = new java.util.ArrayList()
list.add(jack)
list.add(bob)
println list.name
Executing it gives the following output (list of name field values for each Person in the list):
[Jack, Bob]
So my question is what the corresponding java code for calling list.name?
My assumption is that it translates to something like:
list.stream().map(person -> person.name).collect(Collectors.toList())
Can somebody explain what exactly happens when i call list.name?
Thanks in advance!
Your code
list.property
is the shortest way to write this. What groovy implies here is the use of the spread operator:
list*.property
(note the * there). And .property could be short here for .getProperty(), for an implicit call to the getter).
So your assumption is correct, that this is the eager collection of the values .getProperty() returns into an ArrayList.
Related
I have a list of records (record is a case class). I am trying to simultaneously update all of the records in the list (using the copy function) and return a list of the updated records.
I tried to use a foreach method but it's not allowing me to produce the list as a result.
This is what I tried so far, I'm not sure if any of this is right
def update_record(record: List[Rec]): List[Rec] = {
val result = record.foreach(r => {
r.copy(firstname = get_firstname(r, record), lastname = get_lastname(r, record))
})
result
}
but result doesn't produce a list so I'm not sure what to do now.
You just need to use map instead of foreach.
def update_record(record: List[Rec]: List[Rec] =
record.map { r =>
r.copy(firstname = get_firstname(r, record), lastname = get_lastname(r, record))
}
Anyways, it would be good to follow some tutorial or course or read a book about the language. This is just basic knowledge of the standard library.
Some links that may be useful:
Scala tour.
Scala book.
Scaladoc.
Scala style guide.
I'm trying to create a game using python, but in my 'class Character:', i would like to do something like:
answer = raw_input('Which class do you want to play')
if answer = list_name[0]
self.stats = list_name
Thank you!
First note that your if statement should have an == instead of =
Also this type of situation is a great time to use python's in statement which will check if a value matches any of the items in your list! You could try something like this:
list_name = ['classA','classB','classC','classD']
answer = raw_input('Which class do you want to play: ')
#Check if the answer is one of the options in your list
if answer in list_name:
my_stats = answer
print 'great, your class is '+my_stats
else:
print 'sorry, ['+answer+'] is not an ok class'
Scala noob i'm afraid:
I have the following declared class variable which will the objects I read from the database:
val options = mutable.LinkedList[DivisionSelectOption]()
I then use JPA to get a List of all rows from a table:
val divisionOptions = em.createNamedQuery("SelectOption.all", classOf[SelectOption]) getResultList
/* Wrap java List in Scala List */
val wrappedOptions = JListWrapper.apply(divisionOptions)
/* Store the wrappedOptions in the class variable */
options += wrappedOptions
However, the last line has an error:
Type Expected: String, actual JListWrapper[SelectOption]
Can anyone help with what I am doing wrong? I'm just trying to populate the options object with the result of the DB call.
Thanks
What (probably) is happening is that a JlistWrapper[SelectOption] isn't a DivisionSelectOption, so the method += isn't applicable to it. That being the case, it is trying other stuff, and giving a final error on this:
options = options + wrappedOptions
That is a rewriting Scala can do to make things like x += 1 work for var x. The + method is present on all objects, but it takes a String as parameter -- that's so one can write stuff like options + ":" and have that work as in Java. But since wrappedOptions isn't a String, it complains.
Roundabout and confusing, I know, and even Odersky regrets his decision with regards to +. Let that be a lesson: if you thing of adding a method to Any, think really hard before doing it.
I have what I believe to be an embarrassingly simple problem, but three hours of googling and checking stackoverflow have not helped.
Let's say I have a very simple piece of code:
def secret_formula(started):
jelly_beans = started*500
jars = jelly_beans/1000
crates = jars/100
return jelly_beans,jars,crates
start_point = 10000
print("We'd have {} beans, {} jars, and {} crates.".format(secret_formula(start_point)))
What happens is I get the "IndexError: tuple index out of range". So I just print the secret_formula function to see what it looks like, and it looks like this:
(5000000, 5000.0, 50.0)
Basically, it is treating the output as one 'thing' (I am still very new, sorry if my language is not correct). My question is, why does it treat it like this and how do I make it pass the three outputs (jelly_beans, jars, and crates) so that it formats the string properly?
Thanks!
The format function of the string take a variable number of argument. The secret_formula function is returning a tuple. You want to convert that to a list of arguments. This is done using the following syntax:
print("We'd have {} beans, {} jars, and {} crates.".format(*secret_formula(start_point)))
The important par is the * character. It tell that you want to convert the following iterable into a list of argument to pass to the function.
I've been using ScalaTest's FeatureSpec for a couple of days now and I'm trying to understand if it's possible to define the following spec using the built-in matchers (and if not, how I can write a suitable custom matcher).
Suppose I have the class Book:
case class Book(val title: String, val author: String)
and in my test I have a List of books:
val books = List(Book("Moby Dick", "Melville"))
Now, I would like to specify that the books list should contain a book with the title "Moby Dick". I would like to write something like:
books should contain (value with title "Moby Dick")
I can't seem to figure out from the docs and code if it's possible to express this requirement in ScalaTest. Has anyone ran into a similar situation?
In the meantime here's a custom matcher you can use:
def containElement[T](right: Matcher[T]) = new Matcher[Seq[T]] {
def apply(left: Seq[T]) = {
val matchResults = left map right
MatchResult(
matchResults.find(_.matches) != None,
matchResults.map(_.failureMessage).mkString(" and "),
matchResults.map(_.negatedFailureMessage).mkString(" and ")
)
}
}
Then you can use the full power of the ScalaTest Have matcher to inspect the fields of your object:
val books = List(Book("Moby Dick", "Melville"),
Book("Billy Budd", "Melville"),
Book("War and Peace", "Tolstoy"))
books should containElement(have('title("Moby Dick")))
books should containElement(have('title("Billy Budd"), 'author("Melville")))
books should containElement(have('title("War and Peace"), 'author("Melville")))
The last one is a failure producing this output:
The title property had value "Moby Dick", instead of its expected value "War and Peace", on object Book(Moby Dick,Melville) and The title property had value "Billy Budd", instead of its expected value "War and Peace", on object Book(Billy Budd,Melville) and The author property had value "Tolstoy", instead of its expected value "Melville", on object Book(War and Peace,Tolstoy)
You can also combine matchers with and or or, use not, etc.
Not currently, though you will be able to do something like this very soon in the future. What you can do now is something like:
books.exists(_.title == "Moby Dick") should be (true)