The Google Guava libraries contains useful utility classes and methods. If we want to convert between ASCII case conventions we can use the CaseFormat
class. The class defines constants for upper and lower case CamelCase, upper and lower case hyphenated and upper case underscore. This means we can convert UPPER_VALUE
to upper-value
with a simple line of code.
import static com.google.common.base.CaseFormat.*;
assert LOWER_CAMEL.to(UPPER_UNDERSCORE, "lowerCase").equals("LOWER_CASE");
assert LOWER_HYPHEN.to(LOWER_UNDERSCORE, "manual-index").equals("manual_index");
assert UPPER_CAMEL.to(LOWER_UNDERSCORE, "UpperCase").equals("upper_case")
Continue reading →
Sometimes I work on Java projects and then I miss the expressiveness of the Groovy language. For example to join elements in a list with a given separator to get a String value we only have to use the following code:
final List names = ['mrhaki', 'JDriven', 'Groovy Rocks!']
assert names.join(',') == 'mrhaki,JDriven,Groovy Rocks!'
Continue reading →
One of the great things of Gradle is that the build scripts are code. We can use all the features of the Groovy language, we can refactor our build scripts to make them more maintainable, we can use variables and properties to define values and much more, just like our application code. In this post we see how we can create a class to define a version in our build script. To set the version of a Gradle project we only have to assign a value to the version
property. Normally we use a String value, but we can also assign an object. Gradle will use the toString()
method of the object to get the String value for a version. In the following build script we define a new class Version
in our build script. We create an instance of the class and assign it to the version
property. With the task printVersion
we can see the value of the version
property:
version = new Version(major: 2, minor: 1, revision: 14)
task printVersion {
doFirst {
println "Project version is $version"
}
}
defaultTasks 'printVersion'
class Version {
int major, minor, revision
String toString() {
"$major.$minor.$revision"
}
}
Continue reading →
The Google Guava libraries has many useful classes and methods. Normally I write code in Groovy and I am used to working with collections in an intuitive way. But sometimes I need to work with Java on my project and then the Google Guava libraries are a great alternative. Suppose I want to check if all elements in a collection apply to a certain condition. In Groovy I would write this:
final List list = ['Groovy', 'Rocks']
assert list.every { it.contains('o') }
Continue reading →