### Gosu Class Invocation Example Source: https://gosu-lang.github.io/docs/.html Illustrates how to instantiate and use a Gosu class, including calling its methods and accessing properties. ```Gosu var c = new SampleClass({"joe", "john", "jack"}) c.printNames("* ") print(c.Names) ``` -------------------------------- ### Basic Gosu Class Structure Source: https://gosu-lang.github.io/docs/.html A fundamental example of a Gosu class, including package, uses statement, variables, constructor, functions, and property getters. ```Gosu package example uses java.util.List class SampleClass { var _names :List // a private class var // A public constructor construct(names :List) { _names = names } // A public function function printNames(prefix :String) { for (n in _names) { print(prefix + n) } } // A public property getter, making 'Names' a read-only property property get Names():List { return _names } } ``` -------------------------------- ### Rendering Gosu String Templates Source: https://gosu-lang.github.io/docs/.html Shows how to render Gosu String Templates either directly to a string or to a writer. It includes examples of calling the static `renderToString()` and `render()` methods with arguments. ```Gosu // render directly to string var str = sample.SampleTemplate.renderToString({"Joe","John","Josh"}) print( str ) // render directly to writer var writer = new java.io.StringWriter() sample.SampleTemplate.render(writer, {"Joe","John","Josh"}) print( writer ) ``` -------------------------------- ### Gosu Block Expression for Filtering and Transformation Source: https://gosu-lang.github.io/docs/.html Shows a more advanced Gosu example chaining 'where' and 'map' block expressions for filtering and transforming strings, followed by sorting and joining. ```Gosu var lstOfStrings ={"This","is","a","list"} var longStrings = lstOfStrings.where( \ s -> s.length >2).map( \ s -> s.toUpperCase()) // converts each string to upper case. .orderBy( \ s -> s ) // there is a .order() method that could be used here instead print( longStrings.join(", ")) // prints "LIST, THIS" ``` -------------------------------- ### Gosu Variable and Type Declarations Source: https://gosu-lang.github.io/docs/.html Demonstrates how Gosu uses type inference for static typing, allowing for concise variable declarations. It shows examples of inferring types for strings and numbers, and explicitly declaring types when inference is not possible. ```gosu var foo ="Foo"// a String var one =1// a Number var guess :String = null// Must declare the type because it can't be inferred ``` -------------------------------- ### Gosu String Enhancements for Type Conversion Source: https://gosu-lang.github.io/docs/.html Provides examples of Gosu's built-in string enhancements for converting strings to other data types like Boolean, Integer, Double, and Date. These enhancements simplify common data parsing tasks. ```Gosu var bool = "true".toBoolean() var integ = "42".toInt() var dubble = "42.2".toDouble() var date = "01/25/2012".toDate() ``` -------------------------------- ### Gosu Program File Execution Source: https://gosu-lang.github.io/docs/.html Shows a basic Gosu program file (.gsp) and how to execute it from the command line. Gosu programs do not require a 'public static void main' entrypoint. ```Gosu print("Hello World!") ``` ```Shell $> gosu hello.gsp Hello World! ``` -------------------------------- ### Gosu Properties vs. Java Fields Source: https://gosu-lang.github.io/docs/.html Demonstrates the concise way Gosu properties abstract field access compared to verbose Java boilerplate. ```Java public class Foo { private String _bar = "bar"; public void setBar(String value) { _bar = value; } public String getBar() { return _bar; } } ``` ```Gosu public class Foo { var _bar :String as Bar = "bar" // the 'as Bar' exposes this field as the property Bar } ``` -------------------------------- ### Gosu Shorthand for Java Collections (List & Map) Source: https://gosu-lang.github.io/docs/.html Compares the verbose Java syntax for creating and populating Lists and Maps with the concise shorthand syntax provided by Gosu. This highlights Gosu's improvements in collection handling. ```Java Map map = new HashMap(); map.put("isOverlyVerbose",true); List> list = new ArrayList>(); list.add( map ); ``` ```Gosu var map = {"isOverlyVerbose" -> false} var list = { map } ``` -------------------------------- ### Gosu Named Arguments Source: https://gosu-lang.github.io/docs/.html Shows how to use named arguments in Gosu to improve code readability, especially with multiple parameters. ```Gosu var c = new SampleClass({"joe", "john", "jack"}) c.printNames(:prefix = "* ") // Example of clarifying complex method calls: // someMethod(true, false, null, false, true) // bwah? // someMethod(:enableLogging = true, :debug = false, :contextObject = null, :trace = false, :summarizeTiming = true) // Oh, I see ``` -------------------------------- ### Gosu Program Classpath and Shebang Source: https://gosu-lang.github.io/docs/.html Demonstrates embedding classpath information and using the Unix shebang standard in Gosu program files for easier execution and dependency management, including Maven coordinates. ```Gosu #! /path/to/gosu classpath "../src,../lib/lib1.jar" print("Here is a library object: ${new SweetLibraryObject()}") ``` ```Gosu #! /path/to/gosu classpath "../src,org.gosu-lang.gosu:sparkgs:0.1.0" print("Here is a library object: ${new SweetLibraryObject()}") ``` ```Shell $> ./my_sweet_gosu_program.gsp Here is a sweet library object: super.SweetLibraryObject@12b27c3 ``` -------------------------------- ### Gosu Using Statement for Resource Management Source: https://gosu-lang.github.io/docs/.html Illustrates the 'using' statement in Gosu for automatic resource management, ensuring that resources implementing Closeable, Lock, IReentrant, or IDisposable are closed properly. ```Gosu using(var conn = getConnection()) { conn.execute("Some advanced SQL") } ``` -------------------------------- ### Using Gosu String Enhancement Source: https://gosu-lang.github.io/docs/.html Illustrates how to use the custom `printWarning` enhancement on a String object in Gosu, demonstrating the direct invocation of the added method. ```Gosu "I'm not sure I can go back to Java".printWarning() ``` -------------------------------- ### Gosu Operators Source: https://gosu-lang.github.io/docs/.html Explains the operators supported in Gosu, highlighting similarities and differences with Java. It covers increment/decrement operators, instance equality (`===`), object equality (`==`), inequality (`<>`), and comparison operators. ```gosu var foo = "Foo" var bar = "Foo" // `==` tests for object equality (like .equals() in Java) if (foo == bar) { print("foo == bar is true") } // `===` tests for instance equality if (foo === bar) { print("foo === bar is true") } else { print("foo === bar is false") } // `<>` is the same as `!=` if (foo <> bar) { print("foo <> bar is true") } else { print("foo <> bar is false") } ``` -------------------------------- ### Gosu String Template (.gst) Definition Source: https://gosu-lang.github.io/docs/.html Defines a sample Gosu String Template file (.gst) with parameters and a loop for generating dynamic content. This demonstrates the structure and syntax of Gosu templates. ```Gosu <%@params( names :String[]) %> All Names: <%for( name in names ){ %> * ${name} <%} %> ``` -------------------------------- ### Gosu Property with Custom Get/Set Logic Source: https://gosu-lang.github.io/docs/.html Illustrates the longer syntax for Gosu properties to include custom logic in getters and setters. ```Gosu public class Foo { var _bar = "bar" property get Bar():String { return _bar } property set Bar(value :String) { if (value == "Foo") throw "That's not a valid value for Bar!" _bar = value } } ``` -------------------------------- ### Gosu Interface Delegation Source: https://gosu-lang.github.io/docs/.html Demonstrates how Gosu classes can delegate interface implementation to a class variable using 'delegate' and 'represents' keywords, promoting composition over inheritance. ```Gosu uses java.lang.Runnable class MyRunnable implements Runnable { // A delegate, exposed as the Impl property delegate _runnable represents Runnable property get Impl(): Runnable { return _runnable } property set Impl(r: Runnable) { _runnable = r } } ``` ```Gosu var x = new MyRunnable() x.Impl = new Runnable() { function run() { print("Hello, Delegation") } } x.run() // prints "Hello, Delegation" ``` -------------------------------- ### Gosu String Literals and Concatenation Source: https://gosu-lang.github.io/docs/.html Illustrates the creation of string literals using both double and single quotes in Gosu, as well as how to concatenate strings. This is fundamental for basic string handling. ```Gosu var s1 ="I'm a String" var s2 = 'I\'m also a String!' var s3 ="Hello" var s4 ="World!" print( s3 + " " + s4 ) // prints "Hello World!" ``` -------------------------------- ### Gosu String Inline Expressions Source: https://gosu-lang.github.io/docs/.html Shows how to use inline expressions with the `${}` syntax within Gosu strings for dynamic content generation. This simplifies string formatting. ```Gosu var s1 ="Hello" var s2 ="World!" print("${s1} ${s2}") // prints "Hello World!" ``` -------------------------------- ### Gosu String Enhancements - Utility Methods Source: https://gosu-lang.github.io/docs/.html Lists several utility enhancements available for Gosu strings, including methods for repetition, newline handling, truncation, padding, and checking for non-blank content. These methods offer convenient string manipulation. ```Gosu // repeat(n:int) // chomp() // chop() // elide(len:int) // rightPad(w:int), leftPad(w:int), center(w:int) // notBlank() ``` -------------------------------- ### Gosu Language Features Overview Source: https://gosu-lang.github.io/docs/index This snippet outlines the key features of the Gosu programming language, highlighting its design principles and benefits for Java developers. It covers aspects like type system, syntax, and interoperability. ```Gosu Gosu was designed with **Java** developers in mind by providing a set of features that allows them to be more productive without sacrificing the benefits of Java's simplicity and type-safety. Features: - Open Type System - Advanced type inference - Program files (mix statements, functions, and classes at the same level) - Structural typing (like TypeScript's interfaces) - Extension methods (aka enhancements) - Java interoperability - Lambda expressions - Classes/Interfaces/Enums - Generics (simplified, reified, declaration site variance) - Composition (via the delegate keyword) - Properties - Null Safety (supports operator ?. etc.) - Named Arguments and Default Parameter Values - A powerful for-statement with user-defined ranges - Member Literals - Object Initializers - Classpath Statement and Shebang (for use with Gosu as a scripting language) ...and more ``` -------------------------------- ### Enhancing Parameterized Types in Gosu Source: https://gosu-lang.github.io/docs/.html Demonstrates how to enhance parameterized types in Gosu, specifically adding an 'allBetween' method to a List of Dates. This showcases Gosu's ability to extend existing generic types. ```Gosu package example uses java.util.*enhancementMyListOfDatesEnhancement:List{function allBetween( start :Date,end:Date):List{this.where( d -> start <= d and d <=end )}} ``` -------------------------------- ### Gosu Default Parameter Values Source: https://gosu-lang.github.io/docs/.html Demonstrates how to define default values for function parameters in Gosu, making them optional. ```Gosu function printNames(prefix :String = "> ") { for (n in _names) { print(prefix + n) } } ``` -------------------------------- ### Gosu Block to Runnable Conversion Source: https://gosu-lang.github.io/docs/.html Demonstrates how a Gosu block can be automatically converted to a Java Runnable interface for seamless interoperability with Java APIs. ```Gosu var r :Runnable r = \->print("This block was converted to a Runnable") ``` -------------------------------- ### Gosu For Loop Iteration Source: https://gosu-lang.github.io/docs/.html Illustrates the Gosu `for` loop, which can iterate over arrays and objects implementing `java.lang.Iterable`. It shows basic iteration, accessing the index, and using the iterator. ```gosu var list = {"one", "two", "three"} // Creates a java.lang.List // Basic iteration for (num in list) { print(num) } // Iteration with index for (num in list index i) { print("${i} : ${num}") // i is an int, and num is still of type String } // Iteration with iterator for (num in list iterator iter) { iter.remove() } print(list) ``` -------------------------------- ### Gosu Program Extends Statement Source: https://gosu-lang.github.io/docs/.html Illustrates how Gosu programs can specify a superclass using the 'extends' keyword, allowing programs to inherit methods and features from a parent class, useful for scripting tools. ```Gosu classpath "org.gosu-lang.gosu:sparkgs:0.1.0" extends sparkgs.SparkFile get('/', \->"Hello World") ``` -------------------------------- ### Gosu Null Safety: Elvis Operator Source: https://gosu-lang.github.io/docs/.html Shows how to use the Elvis operator `?:` in Gosu to provide a default value for null expressions. ```Gosu var myString = getAPossiblyNullString() ?: "default" ``` -------------------------------- ### Gosu Generic Enhancement for List Type Source: https://gosu-lang.github.io/docs/.html Shows a generic Gosu enhancement for `List`, adding a `firstAndLast` method that returns a list containing the first and last elements of the enhanced list. ```Gosu package example uses java.util.List enhancementMyListEnhancement:List{ function firstAndLast():List{ return{this.first(),this.last()} } } ``` -------------------------------- ### Gosu Null Safety: Null-Safe Invocation Source: https://gosu-lang.github.io/docs/.html Demonstrates using the null-safe invocation operator `?.` in Gosu to prevent NullPointerExceptions. ```Gosu var aList = getAListOfStrings() if (aList?.get(0)?.isEmpty()) { print("The first string is empty") } ``` -------------------------------- ### Gosu Block Expression for Filtering Strings Source: https://gosu-lang.github.io/docs/.html Demonstrates using a Gosu block expression with the 'where' function to filter a list of strings based on their length. This showcases the conciseness of Gosu for data manipulation compared to Java. ```Gosu var lstOfStrings ={"This","is","a","list"} var longStrings = lstOfStrings.where( \ s -> s.length >2) print( longStrings.join(", ")) // prints "This, list" ``` -------------------------------- ### Gosu Range Operator in Loops Source: https://gosu-lang.github.io/docs/.html Demonstrates the usage of the Gosu range operator (`..`) within `for` loops for iterating over sequences of numbers. It covers inclusive and exclusive ranges. ```gosu // Range from 0 through 5 (inclusive) for (i in 0..5) { print(i) // Prints 0, 1, 2, 3, 4, 5 } print("---") // Range from 0 up to 5 (exclusive of 5) for (i in 0..|5) { print(i) // Prints 0, 1, 2, 3, 4 } print("---") // Range from 1 up to 5 (exclusive of 0 and 5) for (i in 0|..|5) { print(i) // Prints 1, 2, 3, 4 } ``` -------------------------------- ### Gosu Generic Enhancement for Type Reification Source: https://gosu-lang.github.io/docs/.html Demonstrates type variable reification in Gosu generic enhancements using `toTypedArray()` on `Iterable`, showing how type information is preserved for different types. ```Gosu var lstOfStrings :List={"a","b","c"} var arrOfStrings = lstOfStrings.toTypedArray() //returns a String[] var lstOfObjs :List= lstOfStrings //type variables are covariant in Gosu, see [generics](https://gosu-lang.github.io/generics.html) var arrOfObjs = lstOfObjs.toTypedArray() //returns an Object[] ``` -------------------------------- ### Gosu Iterable Zipping Operation Source: https://gosu-lang.github.io/docs/.html Describes the `zip` method for Gosu Iterables, which combines elements from two Iterables into a list of Pairs based on matching indices. The resulting list's length is determined by the shorter of the two Iterables. ```gosu 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. ``` -------------------------------- ### Gosu Iterable Filtering Operations Source: https://gosu-lang.github.io/docs/.html Explains the `where` and `whereTypeIs` methods for Gosu Iterables. `where` filters elements based on a boolean condition, while `whereTypeIs` filters elements assignable to a specified type. ```gosu 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 ``` -------------------------------- ### Gosu Enhancement for String Type Source: https://gosu-lang.github.io/docs/.html Defines a Gosu enhancement for the `java.lang.String` type, adding a `printWarning` method. This showcases how to extend existing types without explicit imports. ```Gosu package example enhancementMyStringEnhancement:String{ function printWarning(){ print("WARNING: "+this); } } ``` -------------------------------- ### Java Equivalent of Gosu Block Filtering Source: https://gosu-lang.github.io/docs/.html Provides the equivalent Java code for filtering a list of strings based on length, illustrating the verbosity that Gosu's block expressions aim to reduce. ```Java List lstOfStrings =Arrays.asList("This","is","a","list"); List longStrings =newArrayList(); for(String s : lstOfStrings ){ if( s.length()>2){ longStrings.add( s.toUpperCase()); }} Collections.sort(longStrings,newComparator(){ publicint compare(String s,String s2 ){ return s.compareTo( s2 ); }}) StringBuilder sb =newStringBuilder(); for(String s : longStrings ){ if(sb.length()!=0){ sb.append(", "); } sb.append(s); } System.out.println(sb.toString()); ``` -------------------------------- ### Gosu Iterable to Collection Conversions Source: https://gosu-lang.github.io/docs/.html Provides methods to convert an Iterable into various collection types like Collection, List, Set, or a typed Array. If the Iterable is already of the target type, it's cast directly; otherwise, a new collection is created and populated. ```gosu toCollection() : Collection If this Iterable is already a Collection, return this Iterable 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 ``` -------------------------------- ### Gosu Iterable Set Operations Source: https://gosu-lang.github.io/docs/.html Details the `union` method for Gosu Iterables, which computes the set union of the current Iterable with another provided Collection. ```gosu union( that : Collection ) : Set Returns the set union of the two collections ``` -------------------------------- ### Gosu Collection Enhancements for Iterable Source: https://gosu-lang.github.io/docs/.html This section details enhancements to Gosu's collection classes, specifically for java.lang.Iterable. These methods provide functional programming capabilities for collection manipulation. ```Gosu 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 the set disjunction of this collection and the other collection, that is, all elements that are in one collection not the other. each( operation(elt : T) ) Invokes the operation on each element in the Collection. eachWithIndex( operation(elt : T, index : int ) ) Invokes 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 collection 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 produced 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. If 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, an IllegalStateException is thrown. subtract( that : Collection ) : Set Returns the Set subtraction of that Collection from this Collection. ``` -------------------------------- ### Readonly Gosu Property Source: https://gosu-lang.github.io/docs/.html Shows how to declare a readonly property in Gosu using the 'readonly' modifier. ```Gosu public class Foo { var _bar :String as readonly Bar = "bar" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.