Linux gosu что это

Getting Started

There are several options to get started with Gosu depending on your needs

Gosu Lab

Gosu Lab is the easiest way to experiment with Gosu:

  • Download the latest Gosu distribution
  • Set the JAVA_HOME environment variable to JDK 1.8’s home, if needed
  • Unzip the distribution zip, go to the bin folder and double click on gosu.cmd (or gosu if you are using Linux/Mac)

You can try the bundled example projects like the Life game. Just select Life from the Examples pane and run the game by pressing F5.

Gosu Plugin for IntelliJ

The Gosu Plugin for IntelliJ is the recommended way to use Gosu. Keep in mind, however, the latest new language features may not yet be supported in the IntelliJ plugin. If this is the case and you want to experiment with new features, use the Gosu Lab IDE instead (see instructions above).

The plugin is hosted on the IntelliJ IDEA Plugin Repository and you can download it directly from within IntelliJ IDEA. If you installed the old 3.X plugin, delete the plugin and remove the Gosu SDK (File > Project Structure > SDKs), the new plugin does not need it.

Maven and Gradle

If Maven is your thing, here is a simple starter project. Run mvn test to execute the JUnit tests contained within.

Gosu also plays nicely with Gradle — here is another simple starter project. Run gradlew test to execute the JUnit tests contained within.

It is noteworthy that Maven and Gradle projects do not require a local Gosu installation — the respective dependency resolution strategies will download the appropriate Gosu JARs from Maven Central.

. and More

Alternatively, a downloadable archive of simple command-line examples is available here. Check the README file for instructions or view the source.

For the truly impatient, you can evaluate some simple gosu expressions online over on the Play page.

The Basics

Variables and Type Declarations

Gosu is statically typed, but uses type inference to eliminate the vast majority of syntax overhead usually involved with static typing.

Operators

Gosu supports the standard Java operators, with a few minor restrictions and some great bonuses:

  • ++ / — — Just like the Java operators, except they cannot be used within another statement
  • == — Tests for object equality, just like .equals()
  • === — Tests for instance equality
  • <> — The same as !=
  • , > , etc — Standard comparison semantics which also works on java.lang.Comparable objects

Loops

Gosu supports the standard loop variants: for , while , do . while etc.

The Gosu for loop

The for loop in Gosu allows you to iterate over both arrays and anything that implements the java.lang.Iterable interface.

You can also get access to the zero-based index of the loop by including an index variable:

And, if you need access to the iterator for the loop (assuming you are looping over an Iterable ) you can use the iterator keyword:

Here are a few examples making use of the Gosu range operator, ..

Properties

Gosu properties are a way to abstract field access in Gosu classes.

Consider this standard Java boilerplate:

This is a verbose way to simply expose a field, but exposing the field directly has it’s own problems, which is where properties come in.

Here is the same class in Gosu:

If you want the property to be readonly, you can use the readonly modifier:

If you want to add some logic to the get or set of a propery, you can use this longer syntax:

Reading and writing properties works just like accessing a field:

Null Safety

Gosu offers a few helpful tricks to deal with null in your code.

Null Safe Method Invocation

Consider this code:

This code can cause a NullPointerException if either the list or the first string in the list is null. We can address this by using the null-safe invocation operator ?. :

The null safe invocation operator works on both methods and properties.

The Elvis Operator

Sometimes you want a default value if an expression is null. For this use case, Gosu supports the Elvis Operator, ?: :

If getAPossiblyNullString returns null , then the value «default» will be assigned to myString

Читайте также:  Netsdk dll windows 10

Classes

Gosu classes have a familiar syntax. Gosu classes are defined in a file ending with the .gs extension.

Here is a basic Gosu class:

The above code demonstrates the following features:

  • The uses statement, which is identical to the import statement in Java, and makes a class (or package of classes) available for use without qualification.
  • A class variable, declared using the var keyword, just like local variables. Class variables default to private access. You can declare them to be static as well.
  • A class constructor, declared using the construct keyword. This constructor allows you to declare new instances of SampleClass like so: NOTE: Constructors default to public access.
  • A function, declared using the function keyword. This function takes a String argument, and returns no value, so no return type declaration is necessary. It can be invoked like so:
  • A property getter, declared using the property and get keywords. This property returns a list of strings. It can be invoked like so:

Named Arguments & Default Parameters

Gosu supports both named arguments and default parameter values, which can dramatically improve APIs.

Let’s say you wanted to make the argument to printNames() in the class above optional, with a default value of «> » . You would change the parameter declaration to:

And you could now invoke it like so:

Additionally, Gosu allows you to use a named argument syntax when you are working with non-overloaded methods on Gosu classes. You prefix the parameter name with a colon : like so:

Named arguments can be used to clarify code, so you don’t end up with things like this:

Superclasses, Interfaces and Delegates

Gosu classes can extend other classes and implement interfaces just like in Java, using the extends and implements keywords respectively.

One interesting additional feature of Gosu is the ability to delegate the implementation of an interface to a class variable using the delegate and represents keywords:

Note that the class MyRunnable does not declare a run() method, as Runnable requires. Rather, it uses the delegate field _runnable to implement the interface:

Delegates give you a convenient way to favor composition over inheritance.

The Using Statement

The using statement allows you to wrap sections of code that require connections to be closed to be handled automatically when the block finishes. Instead of writing code like this:

In Gosu, you can use the using statement which will handle closing the Connection for you:

The using statement works with the following interfaces:

  • java.io.Closeable
  • java.util.concurrent.locks.Lock
  • gw.lang.IReentrant
  • gw.lang.IDisposable

Gosu Program Files

Gosu doesn’t have the concept of a public static void main(String[] args) entrypoint. Instead, it has programs, which are just bits of code in file ending a .gsp extension.

Here is a simple Hello World application, in the file hello.gsp:

Running the program is simple:

Classpath Statements, Program Extends & Shebang

Gosu programs can embed a classpath in their source, obviating the need for users to pass in a correct classpath externally:

The classpath statement is comma delimited, to avoid system specific dependencies. Each path on it will be added to the classpath. If a path points at a folder and that folder contains jars, all those jars will be added to the classpath as well.

The classpath can also include Maven coordinates, and Gosu will automatically resolve and download them at runtime:

Gosu supports the Unix shebang standard, so your program can begin with #! gosu and Unix-like shells will execute the script with gosu. This makes it much more pleasant to run gosu programs:

No wrapping scripts, no complicated class paths.

Finally, you can set the superclass for a program using the extends keyword:

This allows you to access methods and features in the parent class within your program, and can be used to create simple Gosu-based scripting tools.

Blocks

Blocks (also called closures or lambda expressions) are a simple way to specify an inline function. They have a lot of uses, but they really shine in data structure manipulation:

The \ s -> s.length > 2 is the block. It declares an inline function that says «Given a String s return whether s.length is greater than two».

You can think of it as an inline version of this function:

Blocks allow you to express your logic much more succinctly.

Note that the blocks parameter, s , does not have a type annotation. Gosu does type inference here and figures out that s is a String .

With blocks you can dramatically reduce the amount of code you write when compared with Java.

Consider this complicated Java code:

This can be rewritten in Gosu as:

The Gosu code is clearer and far more brief.

Blocks and Interfaces

Java has many interfaces that contain a single method, which are used as a stand-in for actual closures. In order to facilitate Java interoperability, Gosu blocks and one-method interfaces are automatically converted between one another:

Читайте также:  Друг вокруг для linux

This makes some Java APIs much more pleasant to work with in Gosu.

Enhancements

Enhancements provide a way to add methods and properties to existing types. They are similar to Extension Methods in C#, but do not need to be explicitly imported.

Enhancements are defined in files ending with a .gsx suffix and cannot be defined inline with other Gosu resources. Here is an example enhancement for the type java.lang.String

In enhancements, the this symbol refers to the enhanced type, as opposed to the enhancement itself.

Once an enhancement has been added to your classpath, you can use it in any place you have an object of the enhanced type with no need to explicitly import the enhancement itself. Therefore, using the enhancement above is as simple as just calling the new function anywhere you have a String:

Semantics And Limitations

The above code can be thought of as shorthand for this code:

Enhancements are statically dispatched. This means they cannot be used to implement interfaces or to achieve polymorphism

Generics

Enhancements can be generic, so you can add an enhancement to List :

This method will now be available on all generic lists, and will be properly typed.

Type Variable Reification

Unlike in Java, type variables can be used in general expressions in Gosu. In Enhancements, the type variables are statically, rather than dynamically, reified, much like enhancement methods are statically, rather than dynamically dispatched. The enhancement method toTypedArray():T[] on Iterable demonstrates this:

This «best effort» reification usually does what you want, but can occasionally lead to surprising results.

Enhancing Parameterized Types

A really neat trick with enhancements is that you can enhance parameterized types:

This is how all lists of comparable objects have the sort() method on them, while other lists do not.

Strings & Gosu Templates

String literals in Gosu can be expressed using either double or single quotes:

Strings support concatenation:

Strings also support inline expressions using the $<> syntax:

Because Strings are so common, there are also a bunch of handy enhancements which allows for easy conversion from strings to other types:

Here is a short sample of additional enhancements on String :

  • repeat(n:int) — Repeat the String n times
  • chomp() — Removes a trailing newline from the end of the String, if present
  • chop() — Remove the last character from the String
  • elide(len:int) — Cap the String at a fixed length and replace the last three characters with ‘. ‘ to denote truncation
  • rightPad(w:int) , leftPad(w:int) , center(w:int) — Format the string with additional whitespace
  • notBlank() — Returns true if the string is not null and contains at least one non-whitespace character

Gosu Template Files (.gst)

Gosu supports string templates as first class citizens in the language. A Gosu String Template is a file that ends in the .gst extension.

Here is an example definition, sample.SampleTemplate.gst :

The template explicitly declares the names and types of its arguments using the params() directive

You can render a template by calling the render(w:Writer) or renderToString() static methods:

For each parameter defined in the params directive, an additional argument with that name and type is added to the render() and renderToString() methods.

So, given the template definition above, you could render it like so:

Using templates gives you a type safe way to generate large strings in your applications.

Collections In Gosu

List & Map Syntax

java.util.List and java.util.Map are the two most commonly used data structures in Java. Unfortunately, they can also be fairly verbose to deal with in Java:

Luckily Gosu provides a shorthand syntax for these two types, allowing the above code to simply be written as:

Enhancements

Gosu adds a whole slew of enhancements to collections classes. Here are some of the most useful ones for java.lang.Iterable :

Enhancement Description
allMatch( cond(elt1 : T):boolean ) : boolean Returns true if all elements in this collection match the given condition and false otherwise
average( select:block(elt:T):java.lang.Number ) : BigDecimal Return the average of the mapped value
concat( that : Collection ) : Collection Return a new list that is the concatenation of the two lists
Count() : int Return the number of elements in this Iterable object
countWhere( cond(elt:T):boolean ) : int Return the count of elements in this collection that match the given condition
disjunction( that : Collection ) : Set Returns a the set disjunction of this collection and the other collection, that is, all elements that are in one collection not and not the other
each( operation(elt : T) ) This method will invoke the operation on each element in the Collection
eachWithIndex( operation(elt : T, index : int ) ) This method will invoke the operation on each element in the Collection, passing in the index as well as the element
first() : T Returns the first element in this collection. If the collection is empty, null is returned
firstWhere( cond(elt:T):boolean ) : T Returns the first element in this collection that matches the given condition. If no element matches the criteria, null is returned
fold( aggregator(elt1 : T, elt2 : T):T ) : T Returns all the values of this collection folded into a single value
hasMatch( cond(elt1 : T):boolean ) : boolean Returns true if any elements in this collection match the given condition and false otherwise
intersect( that : Collection ) : Set Return the set intersection of these two collections
join( delimiter : String ) : String Coerces each element in the collecion to a string and joins them together with the given delimiter
last() : T Returns the last element in this collection. If the collection is empty, null is returned
lastWhere( cond(elt:T):boolean ) : T Returns the last element in this collection that matches the given condition. If the collection is empty, null is returned
map ( mapper(elt : T):Q ) : List Maps the values of the collection to a list of values by calling the mapper block on each element
maxBy( comparison(elt : T):Comparable ) : T Returns the maximum value of this collection with respect to the Comparable attribute calculated by the given block. If more than one element has the maximum value, the first element encountered is returned
max ( transform(elt:T):R ) : R Returns the maximum value of the transformed elements
minBy( comparison(elt : T):Comparable ) : T Returns the minimum value of this collection with respect to the Comparable attribute calculated by the given block. If more than one element has the minimum value, the first element encountered is returned
min ( transform(elt:T):R ) : R Returns the minimum value of the transformed elements
partitionUniquely ( mapper(elt : T):Q ) : Map Partitions each element into a Map where the keys are the value produce by the mapper block and the values are the elements of the Collection. If two elements map to the same key an IllegalStateException is thrown
orderBy ( value(elt:T):R ) : IOrderedList Returns a lazily-computed List that consists of the elements of this Collection, ordered by the value mapped to by the given block
orderByDescending ( value(elt:T):R ) : IOrderedList Returns a lazily-computed List that consists of the elements of this Collection, descendingly ordered by the value mapped to by the given block
reduce ( init : V, aggregator(val : V, elt2 : T):V ) : V Returns all the values of this collection down to a single value
removeWhere( cond(elt:T):boolean ) Removes all elements that match the given condition in this collection
retainWhere( cond(elt:T):boolean ) Retains all elements that match the given condition in this collection
reverse() : List Returns a new list of the elements in the collection, in their reverse iteration order
single() : T Returns a single element from this iterable, if only one exists. It no elements are in this iterable, or if there are more than one elements in it, an IllegalStateException is thrown
singleWhere( cond(elt:T):boolean ) : T Returns a single item matching the given condition. If there is no such element or if multiple elements match the condition, and IllegalStateException is thrown
subtract( that : Collection ) : Set Returns the Set subtraction of that Collection from this Collection
toCollection() : Collection If this Iterable is already a Collection, return this Itearble cast to a Collection. Otherwise create a new Collection and copy this Iterable into it
toList() : List If this Iterable is already a List, return this Iterable cast to a List. Otherwise create a new List and copy this Iterable into it
toSet() : Set If this Iterable is already a Set, return this Iterable cast to a Set. Otherwise create a new Set based on this Iterable
toTypedArray() : T[] Returns a strongly-typed array of this Iterable, as opposed to the argumentless Iterable#toArray(), which returns an Object array. This method takes advantage of static reification and, therefore, does not necessarily return an array that matches the theoretical runtime type of the Iterable, if actual reification were supported
union( that : Collection ) : Set Returns the set union of the two collections
where( cond(elt:T): boolean ) : List Returns all the elements of this collection for which the given condition is true
whereTypeIs ( type : Type ) : List Returns all the elements of this collection that are assignable to the given type
zip ( other : Iterable ) : List

>

Returns a list of gw.util.Pair s of elements from matching indices of this and the other Iterables. If one Iterable contains more elements than the other then only return a list of the same length as the shortest of the two Iterables.

Enjoy!

That’s a good overview of what the Gosu language provides for you. Please give it a try and, if you have any questions, hit us up on the Newsgroup!

Источник

Читайте также:  Arch linux mysql installation
Оцените статью