Groovyはいいぞ
@仙台ラボ

おはなしすること

  • Groovyと関連プロダクトのご紹介
  • Groovyのここが好き
  • 関連プロダクトの特徴

Groovyとは

JVM上で動作する動的言語

  • 型を書いても書かなくても良い
    アノテーションで静的チェックも可能
  • 既存のJava資産をそのまま使える
  • 便利機能が追加されてる

最終リリース 2.4.10

2017年3月17日

関連プロダクト

  • Gradle
    Mavenより柔軟なビルドツール
    pluginでScalaもビルドできる
    最終リリース 3.4.1
    2017年3月3日
  • Grails
    Rails風味なWEBフレームワーク
    3からSpringBootベースになった
    かつては Groovy on rails だったらしい
    最終リリース 3.2.7
    2017年3月6日

Groovyのここが好き

コレクション操作

// クロージャは {  }, 引数が一つの場合は 'it' と書ける
(1 .. 10).findAll{ it % 2 }
===> [1, 3, 5, 7, 9]

// 引数が複数ある場合もカッコで括らない
[9, 7, 4 ,1].sort { a, b -> a <=> b }
===> [1, 4, 7, 9]

// Mapを一発で初期化できる。インスタンスはjava標準のMap
[a:1, b:2, c:3].getClass()
===> class java.util.LinkedHashMap

// Listもjava標準のList
[1,2,3,4].getClass()
===> class java.util.ArrayList

数値計算

Java

0.7 + 0.2  + 0.1
====> 0.9999999999999999   // いわゆる丸め誤差

new BigDecimal(0.1)
  .add(BigDecimal.valueOf(0.2))
  .add(BigDecimal.valueOf(0.7))

数値計算

Groovy

0.7 + 0.2 + 0.1
===> 1.0

(0.7).class
===> class java.math.BigDecimal

'+'の場合は 'plus'など、

特定の名前のメソッドを演算子で呼出し可能 

ファイル読み書き

1, 10
1, 20
2, 10
2, 10
1, 10
new File("dat.csv").readLines()
  .collect{ it.split(',') }
  .groupBy{ it.head() }
  .collectEntries{ [it.key, it.value.sum{ it.last().toInteger() }] }
===> [1:40, 2:20]

new File("hoge") << 'a\n' << 'b\n'   // .append でもいい

型チェック1

List<String> func(b) {
  if (b){
    return ''
  }
  else {
    (1 .. 10).collect{ it.toString()}
  }
}
println func(true)
groovy unchecked.groovy
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

型チェック2

@groovy.transform.TypeChecked
List<String> func(b) {
  if (b){
    return ''
  }
  else {
    (1 .. 10).collect{ it.toString()}
  }
}
println func(true)
groovy checked.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/Users/y.yamana/github/groovy-sandbox/checked.groovy: 4: [Static type checking] -
 Cannot return value of type java.lang.String on method ret
urning type java.util.List <String>
 @ line 4, column 12.
       return ''
              ^

1 error

アノテーションで
依存解決

@GrabConfig(systemClassLoader = true)
@Grab('mysql:mysql-connector-java:5.1.40')

import groovy.sql.*
def db = Sql.newInstance("jdbc:mysql://127.0.0.1/", "root", "")
def names = db
  .rows("""
    |SELECT * 
    |FROM INFORMATION_SCHEMA.TABLES 
    |WHERE TABLE_SCHEMA='INFORMATION_SCHEMA'""".stripMargin())
names.each{ println it.table_name }

関連プロダクトの特徴

Gradle

  • ビルドファイルがシンプル
  • 実体はGroovyスクリプトなので、
    タスク中にちょっとした処理を挟める
  • gradle自身のインストールも実行してくれるgradleWrapper
  • daemonで高速化

Gradle

apply plugin: 'java'

group = 'com.mycompany.app'
version = '1.0-SNAPSHOT'

description = """my-app"""

repositories {
     mavenCentral()
}
dependencies {
    testCompile 'junit:junit:3.8.1'
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-app</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>my-app</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

build.gradle

pom.xml

Grails

SpringBootベース
rails風Webフレームワーク

Grails

grails create-app --profile rest-api --inplace
| Application created at /Users/y.yamana/github/groovy-sandbox/grails
grails create-domain-resource Books
| Created grails-app/domain/grails/Books.groovy
| Created src/test/groovy/grails/BooksSpec.groovy
ll
total 80
drwxr-xr-x   9 y.yamana  OPT-SYS\Domain Users   306  3 17 14:30 build
-rw-r--r--   1 y.yamana  OPT-SYS\Domain Users  2182  3 17 14:20 build.gradle
drwxr-xr-x   3 y.yamana  OPT-SYS\Domain Users   102  3 17 14:20 gradle
-rw-r--r--   1 y.yamana  OPT-SYS\Domain Users    73  3 17 14:20 gradle.properties
-rwxr--r--   1 y.yamana  OPT-SYS\Domain Users  4971  3 17 14:20 gradlew
-rwxr--r--   1 y.yamana  OPT-SYS\Domain Users  2404  3 17 14:20 gradlew.bat
drwxr-xr-x  10 y.yamana  OPT-SYS\Domain Users   340  3 17 14:20 grails-app
-rw-r--r--   1 y.yamana  OPT-SYS\Domain Users  5463  3 17 14:20 grails-wrapper.jar
-rwxr--r--   1 y.yamana  OPT-SYS\Domain Users  4622  3 17 14:20 grailsw
-rwxr--r--   1 y.yamana  OPT-SYS\Domain Users  2375  3 17 14:20 grailsw.bat
drwxr-xr-x   5 y.yamana  OPT-SYS\Domain Users   170  3 17 14:20 src

Grails

  1 package grails
  2 
  3 
  4 import grails.rest.*
  5 
  6 @Resource(readOnly = false, formats = ['json', 'xml'])
  7 class Books {
  8   String name
  9   String author
 10   Date   published
 11 }
grails run-app
| Running application...
objc[69949]: Class JavaLaunchHelper is implemented in both /Users/y.yamana/.sdkman/candidates/java/8u121/bin/java and /Users/y.yamana/.sdkman/candidates/java/8u121/jre/lib/libinstrument.dylib. One of the two will be used. Which one is undefined.
Grails application running at http://localhost:8080 in environment: development

Grails

curl http://localhost:8080/books -s | jq .
[]
curl 'http://localhost:8080/books' -H "Content-Type: application/json" \
-d '{"name": "Effective Java (2nd Edition)", "author":"Joshua Bloch", "published":"2008-05-28 00:00:00.000" }' \
-XPOST -s | jq .
{
  "id": 1,
  "author": "Joshua Bloch",
  "name": "Effective Java (2nd Edition)",
  "published": "2008-05-27T15:00:00Z"
}
curl http://localhost:8080/books -s | jq .
[
  {
    "id": 1,
    "author": "Joshua Bloch",
    "name": "Effective Java (2nd Edition)",
    "published": "2008-05-27T15:00:00Z"
  }
]

おまけ

http://sdkman.io/

curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"

sdk list

windowsでもcygwinから利用可能


================================================================================
Available Candidates
================================================================================
q-quit                                  /-search down
j-down                                  ?-search up
k-up                                    h-help
--------------------------------------------------------------------------------
Activator (1.3.10)                                                              

Typesafe is a GUI/CLI tool to help with building reactive applicaions. It uses
sbt (simple build tool) behind the scenes to build, run, and test your project.
It provides a code editing interface, and provides templaes and seeds for you
to clone and use.

                                                         $ sdk install activator
--------------------------------------------------------------------------------
Ant (1.10.0)                                             https://ant.apache.org/

Apache Ant is a Java library and command-line tool whose mission is to drive
processes described in build files as targets and extension points dependent
upon each other. The main known usage of Ant is the build of Java applications.
Ant supplies a number of built-in tasks allowing to compile, assemble, test and
run Java applications. Ant can also be used effectively to build non Java
applications, for instance C or C++ applications. More generally, Ant can be
used to pilot any type of process which can be described in terms of targets
and tasks.

                                                               $ sdk install ant
--------------------------------------------------------------------------------
AsciidoctorJ (1.5.4.1)                                   http://asciidoctor.org/

AsciidoctorJ is the official library for running Asciidoctor on the JVM. Using
AsciidoctorJ, you can convert AsciiDoc content or analyze the structure of a
parsed AsciiDoc document from Java and other JVM languages.

                                                      $ sdk install asciidoctorj
--------------------------------------------------------------------------------
Ceylon (1.3.2)                                           http://ceylon-lang.org/

Ceylon is a modern, modular, statically typed programming language for the Java
and JavaScript virtual machines. The language features a flexible and very
readable syntax, a unique and uncommonly elegant static type system, a powerful
module architecture, and excellent tooling.

                                                            $ sdk install ceylon
--------------------------------------------------------------------------------
CRaSH (1.3.0)                                            http://www.crashub.org/

The Common Reusable SHell (CRaSH) deploys in a Java runtime and provides
interactions with the JVM. Commands are written in Groovy or Java and can be
developed at runtime making the extension of the shell very easy with fast
development cycle.

                                                             $ sdk install crash
--------------------------------------------------------------------------------
Gaiden (1.1)                                       http://kobo.github.io/gaiden/

Gaiden is a tool that makes it easy to create documentation with Markdown.

                                                            $ sdk install gaiden
--------------------------------------------------------------------------------
Glide (0.9.2)                                      http://glide-gae.appspot.com/

Glide makes it incredibly easy to develop apps that harness the power of Google
App Engine for Java using expressiveness of Groovy and sweetness of Gaelyk's
syntactic sugar.

                                                             $ sdk install glide
--------------------------------------------------------------------------------
Gradle (3.4.1)                                                http://gradle.org/

Gradle is a build automation tool that builds upon the concepts of Apache Ant
and Apache Maven and introduces a Groovy-based domain-specific language (DSL)
instead of the more traditional XML form of declaring the project
configuration. Gradle uses a directed acyclic graph (DAG) to determine the
order in which tasks can be run.

                                                            $ sdk install gradle
--------------------------------------------------------------------------------
Grails (3.2.6)                                               https://grails.org/

Grails is a powerful web framework, for the Java platform aimed at multiplying
developers productivity thanks to a Convention-over-Configuration, sensible
defaults and opinionated APIs. It integrates smoothly with the JVM, allowing
you to be immediately productive whilst providing powerful features, including
integrated ORM, Domain-Specific Languages, runtime and compile-time
meta-programming and Asynchronous programming.

                                                            $ sdk install grails
--------------------------------------------------------------------------------
Griffon (1.5.0)                                    http://griffon-framework.org/

Griffon is desktop application development platform for the JVM.Inspired by
Grails, Griffon leverages the use of the Groovy language and concepts like
Convention over Configuration. The Swing toolkit is the default UI toolkit of
choice however others may be used, for example JavaFX.

                                                           $ sdk install griffon
--------------------------------------------------------------------------------
Groovy (2.4.9)                                       http://www.groovy-lang.org/

Groovy is a powerful, optionally typed and dynamic language, with static-typing
and static compilation capabilities, for the Java platform aimed at multiplying
developers' productivity thanks to a concise, familiar and easy to learn
syntax. It integrates smoothly with any Java program, and immediately delivers
to your application powerful features, including scripting capabilities,
Domain-Specific Language authoring, runtime and compile-time meta-programming
and functional programming.

                                                            $ sdk install groovy
--------------------------------------------------------------------------------
GroovyServ (1.1.0)                            https://kobo.github.io/groovyserv/

GroovyServ reduces startup time of the JVM for runnning Groovy significantly.
It depends on your environments, but in most cases, it’s 10 to 20 times faster
than regular Groovy.

                                                        $ sdk install groovyserv
--------------------------------------------------------------------------------
Java (8u121)                       http://www.oracle.com/technetwork/java/javase

Java Platform, Standard Edition (or Java SE) is a widely used platform for
development and deployment of portable code for desktop and server
environments. Java SE uses the object-oriented Java programming language. It is
part of the Java software-platform family. Java SE defines a wide range of
general-purpose APIs – such as Java APIs for the Java Class Library – and also
includes the Java Language Specification and the Java Virtual Machine
Specification. One of the most well-known implementations of Java SE is Oracle
Corporation's Java Development Kit (JDK).

                                                              $ sdk install java
--------------------------------------------------------------------------------
JBake (2.5.1)                                                  http://jbake.org/

JBake is a Java based, open source, static site/blog generator for developers
and designers.

                                                             $ sdk install jbake
--------------------------------------------------------------------------------
JBoss Forge (2.17.0.Final)                               http://forge.jboss.org/

JBoss Forge is the Fastest way to build Maven-based Java EE projects, and
anything else you fancy.

                                                        $ sdk install jbossforge
--------------------------------------------------------------------------------
Kobalt (0.720)                                           http://beust.com/kobalt

Kobalt is a build system inspired by Gradle and Maven. It reuses the best
concepts from these two successful and popular build systems while adding a few
modern features of its own. Kobalt is written entirely in Kotlin and its build
files are valid Kotlin files as well.

                                                            $ sdk install kobalt
--------------------------------------------------------------------------------
Kotlin (1.1)                                             https://kotlinlang.org/

Kotlin is a statically-typed programming language that runs on the Java Virtual
Machine and can also be compiled to JavaScript source code.

                                                            $ sdk install kotlin
--------------------------------------------------------------------------------
Lazybones (0.8.3)                        https://github.com/pledbrook/lazybones/

Lazybones allows you to create a new project structure for any framework or
library for which the tool has a template.

                                                         $ sdk install lazybones
--------------------------------------------------------------------------------
Leiningen (2.7.1)                                          http://leiningen.org/

Leiningen is the easiest way to use Clojure. With a focus on project automation
and declarative configuration, it gets out of your way and lets you focus on
your code.

                                                         $ sdk install leiningen
--------------------------------------------------------------------------------
Maven (3.3.9)                                          https://maven.apache.org/

Apache Maven is a software project management and comprehension tool. Based on
the concept of a project object model (POM), Maven can manage a project's
build, reporting and documentation from a central piece of information.

                                                             $ sdk install maven
--------------------------------------------------------------------------------
sbt (0.13.13)                                          http://www.scala-sbt.org/

SBT is an open source build tool for Scala and Java projects, similar to Java's
Maven or Ant. Its main features are: native support for compiling Scala code
and integrating with many Scala test frameworks; build descriptions written in
Scala using a DSL; dependency management using Ivy (which supports Maven-format
repositories); continuous compilation, testing, and deployment; integration
with the Scala interpreter for rapid iteration and debugging; support for mixed
Java/Scala projects

                                                               $ sdk install sbt
--------------------------------------------------------------------------------
Scala (2.12.1)                                        http://www.scala-lang.org/

Scala is a programming language for general software applications. Scala has
full support for functional programming and a very strong static type system.
This allows programs written in Scala to be very concise and thus smaller in
size than other general-purpose programming languages. Scala source code is
intended to be compiled to Java bytecode, so that the resulting executable code
runs on a Java virtual machine. Java libraries may be used directly in Scala
code and vice versa. Scala is object-oriented, and uses a curly-brace syntax.
Scala has many features of functional programming languages, including
currying, type inference, immutability, lazy evaluation, and pattern matching.
It also has an advanced type system supporting algebraic data types, covariance
and contravariance, higher-order types, and anonymous types. Other features of
Scala include operator overloading, optional parameters, named parameters, raw
strings, and no checked exceptions.

                                                             $ sdk install scala
--------------------------------------------------------------------------------
Spring Boot (1.5.2.RELEASE)               http://projects.spring.io/spring-boot/

Spring Boot takes an opinionated view of building production-ready Spring
applications. It favors convention over configuration and is designed to get
you up and running as quickly as possible.

                                                        $ sdk install springboot
--------------------------------------------------------------------------------
Sshoogr (0.9.25)                             https://github.com/aestasit/sshoogr

Sshoogr is a Groovy based DSL and command line tool for working with remote
servers through SSH.

                                                           $ sdk install sshoogr
--------------------------------------------------------------------------------
Vert.x (3.3.3)                                                  http://vertx.io/

Vert.x is a tool-kit for building reactive applications on the JVM.

                                                             $ sdk install vertx
--------------------------------------------------------------------------------
# groovy, gradle, grails, scala, kotlin ...
sdk install groovy [version]
sdk use scala 2.11

deck

By yohei yamana