Skip to content

Instantly share code, notes, and snippets.

@toby55kij
toby55kij / SimpleCalculatorCLI.groovy
Created July 28, 2010 15:14
JGGUG懇親会のLTで発表した内容のソース
@Grab('jline:jline:0.9.94')
def c = new jline.ConsoleReader()
while (l = c.readLine('$ ')) println "${_ = evaluate(l)}"
println ''
// g100pon #99 JavaとしてもGroovyとしても正当だが結果が異なるコード
// GroovyでもJavaでも動きます
public class Code099 {
public static void main(String[] args) {
//Java:0.6666666666666666,Groovy:0.6666666667
System.out.println(2.0/3);
//おまけ:Java:0,Groovy:0.5
System.out.println(1/2);
}
}
// g100pon #85 ブラウザで任意のURLを表示(OS非依存)
// Java6以降で動作
import java.awt.Desktop
Desktop.getDesktop().browse args[0].toURI()
// g100pon #56 数値型(Javaとの相違点など)
// 実数は指定が無い限りBigDecimal
assert (0.5).class == java.math.BigDecimal
// Float同士の加減乗算の結果はDouble(JavaではFloat)
assert (1f + 2f).class == java.lang.Double
assert (1f - 2f).class == java.lang.Double
assert (1f * 2f).class == java.lang.Double
// Float同士の除算の結果はDouble
assert (1f / 2f).class == java.lang.Double
// 整数同士の除算の結果は実数(Javaでは整数)
// g100pon #65 何でも使えるぜGroovyなswitch-case
def check(value) {
switch (value) {
case 0: println 'zero';break // 普通
case 1..9: println '1to9';break // 範囲指定
case [10, 12, 14]: println '10or12or14';break // リストで指定
case {it instanceof Integer && it % 7 == 0}: println '7,14,21,...';break // クロージャ
case ~/gr.*/: println 'gr*';break // 正規表現
case 'foo': println 'FOO';break // 文字列
case String: println 'String';break // クラス
// g100pon #70 存在しないメソッド/プロパティアクセスをフック
class Some {
def doMethod() {
println "Method!"
}
String name
def methodMissing(String name, args) {
println "method $name ( $args ) is missing!"
}
def propertyMissing(String name) {
// g100pon #58 StringクラスのGDKメソッド
// 1.7.3で追加されたメソッド
// capitalize:先頭文字を大文字化
assert 'foo'.capitalize() == 'Foo'
// expand:タブを空白に展開
assert '¥tabc'.expand() == ' abc' //引数無しの場合タブは8
assert '¥tdef¥tghi'.expand(4) == ' def ghi'
// stripIndent:各行の先頭にある共通な空白を除去
assert ' abc abc¥n def¥n ¥n ghi'.stripIndent() == 'abc abc¥n def¥n¥n ghi'
// stripMargin:各行の先頭に当たる文字が現れるまで空白・コントロール文字を除去
// g100pon #66 Expando使用例
//テスト用メソッド
def testMethod(person) {
//引数personにはプロパティfirstName,familyNameとname()メソッドがあることを前提としている
assert person.name() == "${person.firstName} ${person.familyName}"
}
//Expandoを作成
def person = new Expando()
//プロパティを追加
// g100pon #53 いろいろな型変換(toメソッド、キャスト、as)
// toメソッド
// 文字から数値へ
def a = '123'.toInteger()
assert a.class == Integer
def b = '123.45'.toBigDecimal()
assert b.class == BigDecimal
// 数値から文字へ
@toby55kij
toby55kij / HtmlBuilder.groovy
Created November 12, 2010 12:14
HtmlBuilderをmethodMissingで書き換えてみる。
import groovy.xml.MarkupBuilder
class HtmlBuilder{
BuilderSupport builder
HtmlBuilder(BuilderSupport builder = new MarkupBuilder()){
this.builder = builder
}