6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Groovy]2.4リリース!groovyshがちょっと便利になりました。

Posted at

概要

昨日、Groovyの新メジャーバージョン2.4がリリースされました。
Groovy 2.4 release notes

PivotalがGroovyとGrailsのスポンサーを3月末で終了するとアナウンスされてから数日でのリリースです。
今回の目玉は間違いなくAndroidのサポートです。
コレでAndroid開発が劇的に楽になるはずですね!

しかし、私はAndroidアプリの開発をしたことが無いので、今回は2.4で向上した地味な部分、groovyshに関して書きます。

defが使えるようになりました

いままでgroovyshの中では、defを使って変数の宣言が出来ませんでした。
Groovy2.4からはやっとdefを使って変数が宣言できるようになりました!
早速試してみます。

kkuwana% groovysh
Groovy Shell (2.4.0, JVM: 1.8.0_25)
Type ':help' or ':h' for help.
-------------------------------------------------------------------------------
groovy:000> def hello = "Hello Groovy"
===> Hello Groovy
groovy:000> hello
===> Hello Groovy
groovy:000> String hey = "hey hey Groovy"
===> hey hey Groovy
groovy:000> hey
===> hey hey Groovy
groovy:000> 

ちゃんと動いていますね!
実は、gvm経由でGroovy2.4をインストールした直後は、何故かちゃんと動作しませんでした。
もし動かねぇぞ!っていう場合は、一旦再起動するか、groovysh上で:set interpreterMode trueを実行してみてください。

groovyshに初期状態を与える

どういうことだ?という話ですが、groovysh起動時に事前に準備したコマンドを実行できるようになりました。(。。。なんか前からあったような気がするんですが気のせい?)
具体的には、ユーザのホームディレクトリ中に、.groovy/groovysh.rcというファイルを準備して、その中にGroovyコードを書いておけば、groovyshが起動するときに勝手にその内容を実行してくれます。

例えば以下のようなファイルを準備します。

~/.groovy/groovysh.rc
// groovyshを起動した場所のフルパスを表示する。
println "You are executing groovysh on the ${new File(".").canonicalPath}"

// 当然事前に使いそうだなという変数を宣言しておくことも出来る。
def now = new Date()

これで、適当なディレクトリに移動して、groovyshを実行してみます。
すると。。。?

kkuwana% groovysh
You are executing groovysh on the /var/www/nginx
Groovy Shell (2.4.0, JVM: 1.8.0_25)
Type ':help' or ':h' for help.
-------------------------------------------------------------------------------
groovy:000> now
===> Thu Jan 22 12:01:48 CET 2015
groovy:000> 

groovyshが起動した時にちゃんとメッセージが表示されて更にnowという変数にDateオブジェクトが格納されていますね。

まとめ

特に派手な変化ではありませんが、こういう部分の変更にまでちゃんと手が及んでいるというのは非常にありがたいですね。

参考

Groovysh improvements
Groovy 2.4のgroovyshでは、defが効くようになった。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?