<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>My own tech words... &#187; Groovy</title>
	<atom:link href="http://blog.lucastex.com/category/tech/groovy-tecnologia/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.lucastex.com</link>
	<description></description>
	<lastBuildDate>Fri, 07 Jan 2011 12:43:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Interceptando métodos inexistentes em Groovy</title>
		<link>http://blog.lucastex.com/2009/07/06/interceptando-metodos-inexistentes-em-groovy/</link>
		<comments>http://blog.lucastex.com/2009/07/06/interceptando-metodos-inexistentes-em-groovy/#comments</comments>
		<pubDate>Mon, 06 Jul 2009 18:15:14 +0000</pubDate>
		<dc:creator>lucastex</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[builder]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[html]]></category>

		<guid isPermaLink="false">http://blog.lucastex.com/?p=410</guid>
		<description><![CDATA[As linguagens dinâmicas estão ganhando um espaço considerável hoje em dia. Para dar um exemplo do poder dessas linguagens, criei um exemplo simples em Groovy (linguagem Java que roda &#8220;em cima&#8221; da JVM).
Uma das características dessas linguagens, é poder aproveitar a criatividade do desenvolvedor. Daí temos como exemplo uma função que pode ser definida em [...]]]></description>
			<content:encoded><![CDATA[<p>As linguagens dinâmicas estão ganhando um espaço considerável hoje em dia. Para dar um exemplo do poder dessas linguagens, criei um exemplo simples em Groovy (linguagem Java que roda &#8220;em cima&#8221; da JVM).</p>
<p>Uma das características dessas linguagens, é poder aproveitar a criatividade do desenvolvedor. Daí temos como exemplo uma função que pode ser definida em nossos objetos chamada <strong>methodMissing</strong>. Essa função é chamada quando algum método não encontrado é chamado em algum objeto. Caso não seja definida, aí sim temos o comportamento padrão do Java, uma exception apontando a falta do método.</p>
<p>No <a href="http://twitter.com/lucastex">twitter</a>, o <a href="http://twitter.com/cmilfont/status/2441669599">@cmilfont perguntou ao @fabiokung</a> sobre um builder de HTML que ele tinha feito em ruby com o mesmo princípio. Usar o methodMissing. Quando eu vi <a href="http://gist.github.com/72852">este builder</a>, fiquei pasmo com a simplicidade e objetividade, e tudo isso originou este post. Coloquei alguns tratamentos que não existiam, para valores de atributos das tags.</p>
<p>O exemplo utiliza o poder da função methodMissing para criar um &#8220;Builder&#8221;, ou então um construtor de HTML dinâmico com base em pseudo-métodos chamados pelo cliente. Imaginem a função abaixo:</p>
<pre>def methodMissing(String name, params) {
	if (params[0] instanceof Closure) {
		println "< ${name}>"
		params[0].call()
		println "< / ${name}>"
	} else if (params[0] instanceof String) {
		println "< ${name}>${params[0]}< ${name}>"
	} else if (params[0] instanceof Map) {
		print "< ${name}"
		params[0].each() {chave, valor ->
			print " ${chave}=\"${valor}\""
		}
		if (params.length > 1) {
			if (params[1] instanceof Closure) {
				println ">"
				params[1].call()
				println ""
			}
		} else println " />"
	}
}</pre>
<p>No primeiro if, resgatando o parâmetro do tipo closure, apenas faz a chamada a esta closure, para que o novo método seja chamado entre &#8220;TAGS&#8221; que são o nome do método criado dinâmicamente&#8230; Já no caso do parâmetro ser uma String, é encarada como conteúdo  inteno da tag e renderizada desta maneira.</p>
<p>Se um map for passado como parâmetro, a interpretação é tida como vários atributos da tag html (método inexistente), e caso ainda tenhamos uma outra closure ali como parâmetro, o comportamento é repetido <img src='http://blog.lucastex.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Com este exemplo, poderíamos construir um simples HTML com o seguinte trecho de código (script) groovy:</p>
<pre>html {
    head {
        title "teste de titulo"
    }
    body {
        div(id:3, class:"odd") {
            p "meu texto"
        }
        div id:5, class:"xpto"
    }
}</pre>
<p>Prontinho, a JVM com o trecho acima cria nosso super-mega-ultra-elaborado trecho de HTML:</p>
<pre>
< html >
< head >
< title >teste de titulo< / title >
< / head >
< body >
< div id="3" class="odd" >
< p >meu texto< / p >< / div >
< div id="5" class="xpto" / >
< / body >
< / html >
</pre>
<p>Groovy é uma linguagem de script muito bacana e poderosa, e como roda em cima da JVM, não é nada mais que Java puro. Pode com certeza e MUITA eficiência substituir aqueles scripts shell que temos em algumas aplicações, trazendo para os desenvolvedores mais liberdade (de chamar um jar com funcionalidades, por exemplo), e conforto (de não depender de alguém de infra estrutura, ou de conhecimento em shell script).</p>
<p>Fica aí a dica e o exemplo do poder&#8230;</p>
<p>Valeu!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucastex.com/2009/07/06/interceptando-metodos-inexistentes-em-groovy/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Understanding Groovy Categories</title>
		<link>http://blog.lucastex.com/2009/05/02/understanding-groovy-categories/</link>
		<comments>http://blog.lucastex.com/2009/05/02/understanding-groovy-categories/#comments</comments>
		<pubDate>Sat, 02 May 2009 05:28:18 +0000</pubDate>
		<dc:creator>lucastex</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[categories]]></category>
		<category><![CDATA[core]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.lucastex.com/?p=384</guid>
		<description><![CDATA[Have you ever used Groovy Categories? Do you even know what its stands for? 
Groovy Categories is a great feature from Groovy (inherted from Objective-C) that allows you to have some kind of &#8220;extended&#8221; control on a class. The category just &#8220;add&#8221; some more funcionality to your class when you want. It&#8217;s different from creating [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever used Groovy Categories? Do you even know what its stands for? </p>
<p>Groovy Categories is a great feature from Groovy (inherted from <a href="http://en.wikipedia.org/wiki/Objective-C">Objective-C</a>) that allows you to have some kind of &#8220;extended&#8221; control on a class. The category just &#8220;add&#8221; some more funcionality to your class when you want. It&#8217;s different from creating another class that extends from the first one, this approach holds a little more functionality-oriented talk&#8230; <img src='http://blog.lucastex.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Categories is nothing more than a Groovy class that you&#8217;ve implemented before that effectly adds your functionality. The syntax is very simple and all you have to do, is tell to the runtime environment you&#8217;re now using the category.</p>
<pre class="brush: groovy;">use (the category class you want to use) {
    //all your code here can access the category funcionality
}
//back to normal code</pre>
<p>That&#8217;s it. Groovy Core comes with some Categories (<a href="http://groovy.codehaus.org/api/index.html?groovy/servlet/ServletCategory.html">ServletCategory</a>, <a href="http://groovy.codehaus.org/api/index.html?groovy/xml/dom/DOMCategory.html">DOMCategory</a> and <a href="http://groovy.codehaus.org/api/index.html?org/codehaus/groovy/runtime/TimeCategory.html">TimeCategory</a>). The one we use more is the TimeCategory, that adds some calculation methods for us. </p>
<p>Let&#8217;s imagine we want to add some days in our current date, using Java you remember how you should do, don&#8217;t you? </p>
<p>Get a Calendar Instance, retrieve this calendar&#8217;s date, add the ammount of days using the strangest and creepiest method ever and then get the calendar&#8217;s date again (actually, get only its time and create a date with it):</p>
<pre class="brush: java;">//creepiest method
myCalendarInstance.add(Calendar.DAY_OF_MONTH, 10);</pre>
<p>You can see in the TimeCategory&#8217;s javadoc (link above) that it defines some methods like &#8220;getHours(), getDays(), getMinutes()&#8221;. This methods we don&#8217;t have in some usual Date class, but when we use the TimeCategory object, they just get available for us. The example below show us what should happen when we use the TimeCategory:</p>
<pre class="brush: groovy;">Date now = new Date()
println now //just show when am I <img src='http://blog.lucastex.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> 

use(org.codehaus.groovy.runtime.TimeCategory) {
    now = now + 15.days
}

println now //shows us when we'll be in 15 days!
</pre>
<p>This will be our output after running this small script:</p>
<pre class="brush: bash;">Sat May 02 02:25:57 BRT 2009
Sun May 17 02:25:57 BRT 2009</pre>
<p>That&#8217;s it, try the code above and the others methods the TimeCategory gives to you: years, months, hours, minutes and seconds.</p>
<p>Thanks! Be the first to know when I publish some interesting article <a href="http://feeds2.feedburner.com/lucastex">signing up my feed</a> and <a href="http://twitter.com/lucastex">following me on twitter</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucastex.com/2009/05/02/understanding-groovy-categories/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Changing the default locale for your grails application</title>
		<link>http://blog.lucastex.com/2009/04/20/changing-the-default-locale-for-your-grails-application/</link>
		<comments>http://blog.lucastex.com/2009/04/20/changing-the-default-locale-for-your-grails-application/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 17:57:41 +0000</pubDate>
		<dc:creator>lucastex</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[application]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[locale]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.lucastex.com/?p=378</guid>
		<description><![CDATA[Thank god grails has a wonderful i18n native support. It&#8217;s great change all your application language just by setting one more parameter in the URL (lang). If you do not know this behaviour, check this out. 
But sometimes you have to preset the default language because not all your applications will be in english, yap [...]]]></description>
			<content:encoded><![CDATA[<p>Thank god <a href="http://www.grails.org">grails</a> has a wonderful i18n native support. It&#8217;s great change all your application language just by setting one more parameter in the URL (lang). If you do not know this behaviour, <a href="http://grails.org/doc/1.1/guide/single.html#10.%20Internationalization">check this out</a>. </p>
<p>But sometimes you have to preset the default language because not all your applications will be in english, yap ? To make this you&#8217;ll have to set your localeResolver in your resources.groovy spring configuration file. just add this code to it. (note that my code is setting my language to brazilian portuguese &#8211; pt_BR)</p>
<pre class="brush: groovy;">
//this is your resources.groovy file
//
beans = {
   localeResolver(org.springframework.web.servlet.i18n.SessionLocaleResolver) {
      defaultLocale = new Locale(&quot;pt&quot;,&quot;BR&quot;)
      java.util.Locale.setDefault(defaultLocale)
   }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucastex.com/2009/04/20/changing-the-default-locale-for-your-grails-application/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Another groovier way to access some itens in my list.</title>
		<link>http://blog.lucastex.com/2009/03/10/another-groovier-way-to-access-some-itens-in-my-list/</link>
		<comments>http://blog.lucastex.com/2009/03/10/another-groovier-way-to-access-some-itens-in-my-list/#comments</comments>
		<pubDate>Tue, 10 Mar 2009 15:08:16 +0000</pubDate>
		<dc:creator>lucastex</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.lucastex.com/?p=120</guid>
		<description><![CDATA[Hello,
Yesterday I&#8217;ve posted this post: Uma maneira bem â€˜a-lÃ¡ groovyâ€™ de se acessar o Ãºltimo elemento de uma lista! (English version here) that explains how we can use negative indexes to access the elements on one list using groovy. And a friend of mine, Paulo Suzart, that works with me commented that using Scala he [...]]]></description>
			<content:encoded><![CDATA[<p>Hello,</p>
<p>Yesterday I&#8217;ve posted this post: <a href="http://blog.lucastex.com/2009/03/09/uma-maneira-bem-a-la-groovy-de-se-acessar-o-ultimo-elemento-de-uma-lista/">Uma maneira bem â€˜a-lÃ¡ groovyâ€™ de se acessar o Ãºltimo elemento de uma lista!</a> (<a href="http://blog.lucastex.com/2009/03/09/the-grooviest-way-to-access-the-last-item-in-a-list/">English version here</a>) that explains how we can use negative indexes to access the elements on one list using groovy. And a friend of mine, <a href="http://codemountain.wordpress.com/">Paulo Suzart</a>, that works with me <a href="http://blog.lucastex.com/2009/03/09/uma-maneira-bem-a-la-groovy-de-se-acessar-o-ultimo-elemento-de-uma-lista/#comments">commented</a> that using <a href="http://www.scala-lang.org/">Scala</a> he can have some extra calls one one list.</p>
<blockquote><p>lista.head //first element<br />
lista.last //last element<br />
lista.tail //all elements except the first one</p></blockquote>
<p>I myself do not know scala well, ( except for the times he keeps talking about it! LOL). But this comments submitted me to my textmate to explore the list methods, and I got surprised when I saw all that methods exactly reproduced in groovy. My mistake that I did not posted this way in yesterday&#8217;s post, but here it is:</p>
<blockquote><p>def lista = []<br />
lista &lt;&lt; &#8220;first element&#8221;<br />
lista &lt;&lt; &#8220;second element&#8221;<br />
lista &lt;&lt; &#8220;third element&#8221;</p>
<p>println lista.head() //&#8221;first element&#8221;<br />
println lista.last() //&#8221;third element&#8221;<br />
println lista.tail() //gives me another list, formed by &#8220;second element&#8221; and &#8220;third element&#8221;</p></blockquote>
<p>That&#8217;s it! Hope it helps.</p>
<p>You can follow me on twitter: <a href="http://www.twitter.com/lucastex">twitter.com/lucastex</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucastex.com/2009/03/10/another-groovier-way-to-access-some-itens-in-my-list/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails 1.1 is available!</title>
		<link>http://blog.lucastex.com/2009/03/10/grails-11-is-available/</link>
		<comments>http://blog.lucastex.com/2009/03/10/grails-11-is-available/#comments</comments>
		<pubDate>Tue, 10 Mar 2009 13:58:29 +0000</pubDate>
		<dc:creator>lucastex</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://blog.lucastex.com/?p=116</guid>
		<description><![CDATA[Hello!
Good news for today!! I just got @ work and saw in my twitter that Graeme Rocher just updated Grails with the new Version 1.1. This is awesome!!
Here is his twitt: http://twitter.com/graemerocher/status/1305118282
Grails 1.1 release notes: http://www.grails.org/1.1+Release+Notes
Grails 1.1 documentation: http://grails.org/doc/1.1.x/
Some stuff I really liked and I thing will help the day-by-day development:

GORM is now independent from [...]]]></description>
			<content:encoded><![CDATA[<p>Hello!</p>
<p>Good news for today!! I just got @ work and saw in my twitter that Graeme Rocher just updated Grails with the new Version 1.1. This is awesome!!</p>
<p>Here is his twitt: <a href="http://twitter.com/graemerocher/status/1305118282">http://twitter.com/graemerocher/status/1305118282</a><br />
Grails 1.1 release notes: <a href="http://www.grails.org/1.1+Release+Notes">http://www.grails.org/1.1+Release+Notes</a><br />
Grails 1.1 documentation: <a href="http://grails.org/doc/1.1.x/">http://grails.org/doc/1.1.x/</a></p>
<p>Some stuff I really liked and I thing will help the day-by-day development:</p>
<ul>
<li>GORM is now independent from Grails
<ul>
<li>Yeah, that is correct, now you can use GORM&#8217;s god-blessed-methods in your own groovy project!</li>
</ul>
</li>
</ul>
<ul>
<li>hasMany associations for primitive types
<ul>
<li>You can use hasMany for primitive types, eg. Strings. Remember that time you had to create one domain class just for encapsulate one string? Now you can have this! <img src='http://blog.lucastex.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </li>
</ul>
</li>
</ul>
<ul>
<li>Global plugins
<ul>
<li>For people that knows Ruby and Rails, this will be like a gem. You install the plugin once with the tag -global and will be available for all apps</li>
</ul>
</li>
</ul>
<p>Visit the links above and stay tuned!</p>
<p>You can follow me on twitter: <a href="http://twitter.com/lucastex">http://twitter.com/lucastex</a><br />
Take care!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucastex.com/2009/03/10/grails-11-is-available/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails 1.1 foi lanÃ§ado!!</title>
		<link>http://blog.lucastex.com/2009/03/10/grails-11-foi-lancado/</link>
		<comments>http://blog.lucastex.com/2009/03/10/grails-11-foi-lancado/#comments</comments>
		<pubDate>Tue, 10 Mar 2009 13:52:50 +0000</pubDate>
		<dc:creator>lucastex</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://blog.lucastex.com/?p=113</guid>
		<description><![CDATA[Oi,
Uma Ã³tima notÃ­cia para a manhÃ£ de hoje!!! O framework Grails teve sua versÃ£o 1.1 lanÃ§ada agora cedo! Ontem mesmo eu estava conversando com o Carlin e ele me perguntou se eu sabia quando iria ser liberada&#8230; Hoje cedo antes de sair de casa para vir para o trabalho, vi que o Graeme Rocher tava [...]]]></description>
			<content:encoded><![CDATA[<p>Oi,</p>
<p>Uma Ã³tima notÃ­cia para a manhÃ£ de hoje!!! O framework Grails teve sua versÃ£o 1.1 lanÃ§ada agora cedo! Ontem mesmo eu estava conversando com o Carlin e ele me perguntou se eu sabia quando iria ser liberada&#8230; Hoje cedo antes de sair de casa para vir para o trabalho, vi que o Graeme Rocher tava trabalhando em cima das pÃ¡ginas do wiki do grails.org&#8230; Bem na pÃ¡gina de Releases&#8230;. EntÃ£o o invitÃ¡vel estava para acontecer, precisariamos esperar apenas mais um pouco e terÃ­amos a versÃ£o por lÃ¡&#8230;.</p>
<p>1 hora depois, cheguei no trabalho e quando vi! Tava lÃ¡ no meu twitter o anÃºncio por parte dele: <a href="http://twitter.com/graemerocher/status/1305118282">http://twitter.com/graemerocher/status/1305118282</a><br />
O release notes estÃ¡ disponÃ­vel em: <a href="http://www.grails.org/1.1+Release+Notes">http://www.grails.org/1.1+Release+Notes</a> e a documentaÃ§Ã£o estÃ¡ em: <a href="http://grails.org/doc/1.1.x/">http://grails.org/doc/1.1.x/</a>. TÃ¡ com muita coisa legal, das quais para &#8220;facilitar&#8221; o dia a dia, 3 sÃ£o bem legais:</p>
<ul>
<li>GORM independente de Grails
<ul>
<li>Agora vocÃª pode usar o GORM em seu projeto Groovy, sem ter que depender de toda a estrutura do Grails!</li>
</ul>
</li>
</ul>
<ul>
<li>AssociaÃ§Ã£o has-many de tipos primitivos
<ul>
<li>Isso!! Agora Ã© possÃ­vel ter um hasMany de Strings por exemplo! Antes tinhamos que criar uma classe que iria encapsular a string&#8230; <img src='http://blog.lucastex.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ul>
</li>
</ul>
<ul>
<li>Plugins globais
<ul>
<li>Para quem conhece ruby, seria como se fosse uma gem, os plugins sÃ£o instalados uma vez sÃ³ com a flag -global e ficam disponÃ­vels para todos os projetos!</li>
</ul>
</li>
</ul>
<p>Confiram jÃ¡ no link acima!</p>
<p>Para quem quiser, pode me seguir no twitter e receber as atualizaÃ§Ãµes: <a href="http://twitter.com/lucastex">http://twitter.com/lucastex</a><br />
AbraÃ§o!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucastex.com/2009/03/10/grails-11-foi-lancado/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uma maneira bem &#8216;a-lÃ¡ groovy&#8217; de se acessar o Ãºltimo elemento de uma lista!</title>
		<link>http://blog.lucastex.com/2009/03/09/uma-maneira-bem-a-la-groovy-de-se-acessar-o-ultimo-elemento-de-uma-lista/</link>
		<comments>http://blog.lucastex.com/2009/03/09/uma-maneira-bem-a-la-groovy-de-se-acessar-o-ultimo-elemento-de-uma-lista/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 13:38:26 +0000</pubDate>
		<dc:creator>lucastex</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">http://blog.lucastex.com/?p=104</guid>
		<description><![CDATA[Oi,
Brincando com groovy e lendo alguns artigos durante o fim de semana na internet, vi umas coisas bacanas que facilitam o uso desta linguagem!
Uma coisa que achei bem legal foi uma dica de como acessar uma lista &#8220;de trÃ¡s pra frente&#8221;. Isso mesmo, as vezes a gente precisa acessar o Ãºltimo elemento de uma lista [...]]]></description>
			<content:encoded><![CDATA[<p>Oi,</p>
<p>Brincando com groovy e lendo alguns artigos durante o fim de semana na internet, vi umas coisas bacanas que facilitam o uso desta linguagem!</p>
<p>Uma coisa que achei bem legal foi uma dica de como acessar uma lista &#8220;de trÃ¡s pra frente&#8221;. Isso mesmo, as vezes a gente precisa acessar o Ãºltimo elemento de uma lista certo? Como farÃ­amos?</p>
<p>Vamos imaginar a lista abaixo:</p>
<blockquote><p><strong><em>def lista = []<br />
lista &lt;&lt; â€œfirst itemâ€<br />
lista &lt;&lt; â€œsecond itemâ€<br />
lista &lt;&lt; â€œthird itemâ€</em></strong></p></blockquote>
<p>Se eu quisesse imprimir seu conteudo para verificar, teria:</p>
<blockquote><p><em><strong>println lista[0] // â€œfirst itemâ€<br />
println lista[1] // â€œsecond itemâ€<br />
println lista[2] // â€œthird itemâ€</strong></em></p></blockquote>
<p>Para acessar o Ãºltimo termo, sem delongas irÃ­amos ter que chamar posicionalmente o Ãºltimo elemento da lista, e para isso terÃ­amos que conhecer seu tamanho. TerÃ­amos:</p>
<blockquote><p><em><strong>lista.get(lista.size()-1); //Java<br />
lista[lista.size -1] //groovy</strong></em></p></blockquote>
<p>Certo? A coisa bacana Ã© que groovy tem todos os Ã­ndices de um array/lista espelhados para a sua forma negativa. Ou seja. Se vocÃª acessar a segunda posiÃ§Ã£o (lista[1]), irÃ¡ ir para frente com o nÃºmero inteiro. Se acessar a segunda posiÃ§Ã£o negativa (lista[-2]), irÃ¡ percorrer o segundo elemento de trÃ¡s para frente!</p>
<p>Ou seja, para acessar o Ãºltimo elemento da lista, a forma mais rÃ¡pida, fÃ¡cil e com cheiro de groovy Ã© fazer:</p>
<blockquote><p><strong><em>println lista[-1] //&#8221;third item&#8221;<br />
</em></strong></p></blockquote>
<p>Bacana hein! Valeu!</p>
<p>[]s,</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucastex.com/2009/03/09/uma-maneira-bem-a-la-groovy-de-se-acessar-o-ultimo-elemento-de-uma-lista/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The grooviest way to access the last item in a list</title>
		<link>http://blog.lucastex.com/2009/03/09/the-grooviest-way-to-access-the-last-item-in-a-list/</link>
		<comments>http://blog.lucastex.com/2009/03/09/the-grooviest-way-to-access-the-last-item-in-a-list/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 13:28:16 +0000</pubDate>
		<dc:creator>lucastex</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[fuuny]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">http://blog.lucastex.com/?p=102</guid>
		<description><![CDATA[Hey!
Do you know that groovy provides a fuuny way to access the last item in a list? Let&#8217;s say you have the snippet above:
def lista = []
lista &#60;&#60; &#8220;first item&#8221;
lista &#60;&#60; &#8220;second item&#8221;
lista &#60;&#60; &#8220;third item&#8221;
println lista[0] // &#8220;first item&#8221;
println lista[1] // &#8220;second item&#8221;
println lista[2] // &#8220;third item&#8221;
That&#8217;s ok hÃ£. If you are using Java [...]]]></description>
			<content:encoded><![CDATA[<p>Hey!</p>
<p>Do you know that groovy provides a fuuny way to access the last item in a list? Let&#8217;s say you have the snippet above:</p>
<blockquote><p>def lista = []<br />
lista &lt;&lt; &#8220;first item&#8221;<br />
lista &lt;&lt; &#8220;second item&#8221;<br />
lista &lt;&lt; &#8220;third item&#8221;</p>
<p>println lista[0] // &#8220;first item&#8221;<br />
println lista[1] // &#8220;second item&#8221;<br />
println lista[2] // &#8220;third item&#8221;</p></blockquote>
<p>That&#8217;s ok hÃ£. If you are using Java and needs to access the last item in this list, what should you do? I bet would be something like this (that is applicable to groovy):</p>
<blockquote><p>lista.get(lista.size()-1); //Java<br />
lista[lista.size -1] //groovy</p></blockquote>
<p>I said &#8220;applicable&#8221; but doing this does not make me feel &#8220;groovier&#8221;&#8230; How about this trick?</p>
<blockquote><p>lista[-1] //&#8221;third item&#8221;</p></blockquote>
<p>That&#8217;s it! The indexes inside a list in groovy are &#8220;mirrored&#8221; backwards, so you can access the &#8220;first item from back to front&#8221; using the first negative integer! This is applicable to the rest of the entries:</p>
<blockquote><p>println lista[-1] // &#8220;third item&#8221;<br />
println lista[-2] // &#8220;second item&#8221;<br />
println lista[-3] // &#8220;first item&#8221;</p></blockquote>
<p>Take care!</p>
<p>[]s,</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucastex.com/2009/03/09/the-grooviest-way-to-access-the-last-item-in-a-list/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

