Scala 2.10 Reflection Examples Essays

Changes in Version 2.12.0

Please consult the Scala 2.12.0 release notes.

Changes in Version 2.11

Please consult the Scala 2.11.1 release notes.

Changes in Version 2.10.0

The Scala 2.10.0 codebase includes the following new features and changes:

Value Classes

A class may now extend to make it behave like a struct type (restrictions apply). See: http://docs.scala-lang.org/overviews/core/value-classes.html

Implicit Classes

The modifier now also applies to class definitions to reduce the boilerplate of implicit wrappers. See: http://docs.scala-lang.org/sips/pending/implicit-classes.html

String Interpolation

Example:

See more: http://docs.scala-lang.org/overviews/core/string-interpolation.html

Futures and Promises

Asynchronously get some JSON:

See more: http://docs.scala-lang.org/overviews/core/futures.html

Dynamic and applyDynamic

becomes if ’s type does not define a , but is a subtype of See: http://docs.scala-lang.org/sips/pending/type-dynamic.html

Dependent method types

New ByteCode emitter based on ASM

  • Can target JDK 1.5, 1.6 and 1.7
  • Emits 1.6 bytecode by default
  • Old 1.5 backend is deprecated

A new Pattern Matcher

  • rewritten from scratch to generate more robust code (no more exponential blow-up!)
  • code generation and analyses are now independent (the latter can be turned off with -Xno-patmat-analysis)

Scaladoc Improvements

  • Implicits (-implicits flag)
  • Diagrams (-diagrams flag, requires graphviz)
  • Groups (-groups)

Modularized Language features

Get on top of the advanced Scala features used in your codebase by explicitly importing them. See: http://docs.scala-lang.org/sips/pending/modularizing-language-features.html

Parallel Collections are now configurable with custom thread pools

See: http://docs.scala-lang.org/overviews/parallel-collections/overview.html

Akka Actors now part of the distribution

The original Scala actors are now deprecated. See the actors migration project for more information.

Performance Improvements

  • Faster inliner
  • is now O(1)
  • Update of library
  • Fixes in immutable /
  • Improvements to s
  • Addition of and
  • Addition of + type classes for extension methods
  • Deprecations and cleanup
  • Floating point and octal literal syntax deprecation
  • Removed
  • Experimental features

The following exciting – experimental – features are part of 2.10.0:

Scala Reflection

See: https://docs.google.com/document/d/1Z1VhhNPplbUpaZPIYdc0_EUv5RiGQ2X4oqp0i-vz1qw/edit#heading=h.pqwdkl

Macros

See: http://docs.scala-lang.org/overviews/macros/overview.html

The API is subject to (possibly major) changes in the 2.11.x series, but don’t let that stop you from experimenting with them! A lot of developers have already come up with very cool applications for them.

Changes in Version 2.9.1 to 2.9.2

No language changes were introduced.

Changes in Version 2.9.0 (12-May-2011) {: #2.9.0 }

The Scala 2.9.0 codebase includes the following new features and changes:

Parallel Collections

Every collection may be converted into a corresponding parallel collection with the new method. Parallel collections utilize multicore processors by implementing bulk operations such as , , etc. in parallel. Parallel collections are located in the package .

Depending on the collection in question, may require copying the underlying dataset to create a parallel collection. However, specific collections share their underlying dataset with a parallel collection, making a constant time operation.

Currently available parallel collections are:

  • parallel arrays -
  • parallel ranges -
  • parallel hash maps -
  • parallel hash sets -
  • parallel hash tries -
  • parallel vectors -

The method is used to convert from a parallel collection to a corresponding sequential collection. This method is always efficient (O(1)).

The App Trait

The trait is a safer, more powerful alternative to the previous trait, which has now been deprecated. The new recommended way to write a top-level application is like this:

Objects inheriting from the old trait were almost as convenient to write, but were not thread-safe and were often not optimized by the VM, since the application’s body was execited as part of of the object’s initialization sequence. Objects inheriting the trait instead make use of Scala 2.9’s delayed initialization feature to execute the whole body as part of an inherited method. Another new feature of the scheme is that command line arguments are now accessible via the value (which is inherited from trait )

The DelayedInit Trait

The trait provides another tool to customize initialization sequences of classes and objects. If a class or object inherits from this trait, all its initialization code is packed in a closure and forwarded as an argument to a method named which is defined as an abstract method in trait .

Implementations of have thus full freedom when to execute the initialization code. For instance, Scala’s new trait stores all initialization sequences in an internal buffer and executes them when the object’s method is called.

Note that only initialization code contained in classes and objects is passed to ; initialization code contained in traits is not affected.

Repl Improvements

Improvements in jline, the repl input handler. More robust cursor handling, bash-style ctrl-R history search, new commands like , , . On platforms with the necessary runtime support, will disassemble any class including repl-defined ones. A long-running repl command can now be interrupted via ctrl-C without terminating the repl session. Improved programmability: the repl classloader exposes repl-defined classes via their given names.

Scala Runner

Scala code can now be executed in any of the following ways:

  • will run the main class, similar to java -jar
  • will run the main method of that class
  • will run the script contents as a scala script
  • will, if the contents are not a script, find a single main method in a top level object and run that. This allows the same file to be used with scalac and to be run directly.
  • will create a jar file with the compiled source, which is then reusable and can be run as

Java Interop

  • The annotation is now supported.
  • Various fixes in and for smoother interoperation.
  • Primitive types and their boxed versions are now implicitly converted bidirectionally.

Other features

Generalized try-catch-finally

trybodycatchhandlerfinallycleanup

Here, body and cleanup can be arbitrary expressions, and handler can be any expression which evaluates to a valid exception handler (which is: ).

New packages

and , which are imported from .

New methods in collections

, , , , , , , ,

AnyRef specialization

It is now possible to specialize on type parameters for subtypes of (, which allows for more efficient array indexing and updates.

Changes in Version 2.8.1

No language changes were introduced.

Changes in Version 2.8.0 (14-Jul-2010) {: #2.8.0 }

Scala 2.8.0 is a significantly innovative release, which contains a large amount of fixes and introduces many new features:

Redesigned collection library

The collection library has undergone a complete overhaul for Scala 2.8, offering a more coherent and efficient design, while maintaining virtually complete compatibility with existing sources. Detailed information here.

New array implementation, manifests for polymorphic arrays

Handling of arrays has been simplified and optimized in Scala 2.8. The previous compiler magic has been replaced by a more systematic and predictable implementation in terms of implicit conversions. Detailed information here.

Type specialization

Scala 2.8 adds specialized type parameters, which enable the compiler to generate transparently multiple versions of a given definition, and to use the most specific version whenever the static type information at a call site allows it. Detailed information here.

Named and default arguments

Named arguments improve the readability of method calls with many arguments. Default arguments reduce code duplication, and enable “copy” methods for case classes, useful to generate quickly modified copies of case classes. Detailed information here.

Package objects

Packages can now contain besides classes and objects also methods, fields or type aliases. These are added to a package by declaring a package object. More capabilities might be added to package objects in subsequent releases.

Beefed up Scala Swing libraries, better documentation

Components publish key events, input events can be consumed, refactored window subhierarchy, additional demos, Swing listeners are installed lazily, more complete component caching, minor refactorings, bugfixes, more Scaladocs. Detailed information here.

Revamped REPL

Many bugfixes. Tab-completion for all packages on the classpath, as well as object and instance methods and fields, including type aliases and package objects. Searchable history, integrated shell access, and a power mode which offers direct access to compiler internals.

Implicits changes

We have refined the implicit resolution process so that resolution is now able to determine type variables.

Improved equality

Equality across numeric types is to be consistent across all the primitives types, while also adhering to the equals/hashCode contract. Numeric comparisons will have the same results as they would between Java primitives.

Packrat parser combinators

With support for packrat parsing, parser combinators are now able to handle left-recursive grammars and will show improved performance for ambiguous productions.

Improved XML library

Many bugfixes.

Type constructor inference

Type inference has been extended to deal with type constructors, so that, in certain cases, you can omit type parameter lists that contain higher-kinded types (aka type constructors, e.g., ).

Improved Annotations

Scala 2.8 adds support for nested java annotations. For annotations on fields, it is now possible to specify which synthetic members (getter / setter) will have the annotation. Documentation about Scala annotations can be found here.

Enhanced actors

New Reactors provide more lightweight, purely event-based actors with optional, implicit sender identification. Support for actors with daemon-style semantics was added. Actors can be configured to use the efficient JSR166y fork/join pool, resulting in significant performance improvements on 1.6 JVMs. Schedulers are now pluggable and easier to customize.

Support for continuations

Continuations are supported by a compiler plugin, which is now supported as part of the main distribution.

Internal improvements

New presentation compiler

This new infrastructure, within the Scala compiler, enables IDEs to hook into the compiler to find efficiently information about the structure of the program under editing. This new code offers a better platform for the development of IDE plugins.

New build manager

The new feature used by for example Eclipse to detect intelligently changes in the files and compile only necessary Scala sources, instead of performing clean build on whole projects. This technique enables to significantly reduce the compilation time on bigger projects.

Speed improvements

The compiler now runs as optimised code. In addition, a number of improvements and fine-tunings have further improved the compiler speed up to 50%.

Additional tools

Scaladoc 2

A new look-and-feel, automatic comments expansion and wiki-like syntax, as well as compile-time error checking.

Sbaz 2

Sbaz includes many bug fixes and enhancements. It now gives better feedback to the user during lengthy downloads and while diagnosing dependency audits, which in turn have been re-factored and enhanced. Sbaz should work properly on Windows using either cmd or cygwin, and is now capable of reliably updating itself. Support for pack200 has been added, in some cases reducing file sizes up to 70%.

Scalap

A new , contributed by the community, is included. The new is aware of package objects and can decompile them by using .

Scala IDE for Eclipse

The IDE has been extensively reworked with much functionality moved into the Scala compiler where it can be better maintained and reused by non-Eclipse IDEs and other tools. The integration with Eclipse’s JDT has been deepened, and much previously Scala-specific behaviour and functionality is now provided directly by the JDT leading to across the board improvements. The Scala IDE for Eclipse is now hosted at Assembla.

Changes in 2.7.3 to 2.7.7

No language changes were introduced.

Changes in Version 2.7.2 (10-Nov-2008) {: #2.7.2 }

Generic Signatures

The Scala compiler now generates Java’s generic signatures, so that Scala generics are visible to Java.

Java/Scala Combined Projects

The compiler can now parse (but not translate) Java source files. This makes it possible to have mixed Java/Scala projects with recursive dependencies between them. In such a project, you can submit first all the Java and Scala sources to the Scala compiler. In a second step, the Java sources are compiled using the Scala generated .class files and the Scala sources are compiled again using the Java generated .class files.

ScalaSwing

Another major addition is the first beta version of the ScalaSwing library, which is now bundled with the distribution.

Scala Collections

There are new implementations of collection classes, contributed by David MacIver: , , and (immutable), ArrayStack and (mutable).

Changes in Version 2.7.1 (09-Apr-2008) {: #2.7.1 }

Change in Scoping Rules for Wildcard Placeholders in Types

A wildcard in a type now binds to the closest enclosing type application.

For example is now equivalent to the existential type

In version 2.7.0, the type expanded instead to

The new convention corresponds exactly to the way wildcards in Java are interpreted.

No Contractiveness Requirement for Implicits

The contractiveness requirement for implicit method definitions has been dropped. Instead it is checked for each implicit expansion individually that the expansion does not result in a cycle or a tree of infinitely growing types.

Changes in Version 2.7.0 (07-Feb-2008) {: #2.7.0 }

Java Generics

Scala now supports Java generic types by default:

  • A generic type in Java such as is translated to a generic type in Scala: .
  • A wildcard type such as is translated to . This is itself a shorthand for the existential type .
  • A raw type in Java such as is translated to , which is a shorthand for .

This translation works if is specified, which is the new default. For any other target, Java generics are not recognized. To ensure upgradability of Scala codebases, extraneous type parameters for Java classes under scalac are simply ignored. For instance, when compiling with , a Scala type such as is simply treated as the unparameterized type >.

Case Classes

The Scala compiler generates now for every case class a companion extractor object. For instance, given the case class:

the following companion object is generated:

If the object exists already, only the and methods are added to it.

Three restrictions on case classes have been removed:

  • Case classes can now inherit from other case classes.

  • Case classes may now be
  • Case classes may now come with companion objects:

Removed features

The following deprecated features have been removed from the standard Scala library:

RemovedUse instead
and (object ) and (available since 2.3.0)
element and arity (class ) and
and (class ) and

Changes in Version 2.6.1 (30-Nov-2007) {: #2.6.1 }

Mutable variables introduced by pattern binding

Mutable variables can now be introduced by a pattern matching definition, just like values can. For example:

Self-types

Self types can now be introduced without defining an alias name for . For example:

Changes in Version 2.6 (27-Jul-2007) {: #2.6.0 }

Existential types

It is now possible to define existential types using the new keyword . An existential type has the form where is a sequence of value and/or type declarations. Given the class definitions

one may for example write the following existential types

Lazy values

It is now possible to define lazy value declarations using the new modifier .

Structural types

It is now possible to declare structural types using type refinements. For example:

Deprecated features

  • The old-style syntax of for-comprehensions has been deprecated.
  • The clause has been deprecated; use instead.
  • for unapplied methods has been deprecated; use instead.

Changes in Version 2.5 (02-May-2007) {: #2.5.0 }

Type constructor polymorphism

Type parameters and abstract type members can now also abstract over type constructors. This allows a more precise interface:

This definition of makes explicit that mapping a function over a certain structure (e.g., a >) will yield the same structure (containing different elements).

Early object initialization

It is now possible to initialize some fields of an object before any parent constructors are called. This is particularly useful for traits, which do not have normal constructor parameters. For example:

In the code above, the field is initialized before the constructor of is called. Therefore, field in class is properly initialized to .

-comprehensions, revised

The syntax of -comprehensions has been changed. For example:

is now written

Thus a -comprehension now starts with a (possibly guarded) generator followed by one or more enumerators which can be either a (possibly guarded) generator, a guard or a local value definition.

The old syntax is still available but will be deprecated in the future.

Implicit anonymous functions

It is now possible to define anonymous functions using underscores in parameter position. For instance, the expressions in the left column are each function values which expand to the anonymous functions on their right.

As a special case, a partially unapplied method is now designated instead of the previous notation .

The new notation will displace the special syntax forms for abstracting over method receivers and for treating an unapplied method as a function value. For the time being, the old syntax forms are still available, but they will be deprecated in the future.

Pattern matching anonymous functions, refined

It is now possible to use case clauses to define a function value directly for functions of arities greater than one. Previously, only unary functions could be defined that way. For example:

Changes in Version 2.4 (09-Mar-2007) {: #2.4.0 }

Object-local private and protected

The and modifiers now accept a qualifier. A definition which is labelled is private, and in addition can be accessed only from within the current object. That is, the only legal prefixes for are or . Analogously, a definition which is labelled is protected, and in addition can be accessed only from within the current object.

Tuples, revised

The syntax for tuples has been changed from to . For any sequence of types T1, …, Tn,

T1, …, Tn is a shorthand for T1, …, Tn.

Analogously, for any sequence of expressions or patterns x1, …, xn,

x1, …, xn is a shorthand for x1, …, xn.

Access modifiers for primary constructors

The primary constructor of a class can now be marked or . If such an access modifier is given, it comes between the name of the class and its value parameters. For example:

Annotations

The support for attributes has been extended and its syntax changed. Attributes are now called annotations. The syntax has been changed to follow Java’s conventions, e.g. instead of . The old syntax is still available but will be deprecated in the future.

Annotations are now serialized so that they can be read by compile-time or run-time tools. Class has two sub-traits which are used to indicate how annotations are retained. Instances of an annotation class inheriting from trait will be stored in the generated class files. Instances of an annotation class inheriting from trait will be visible to the Scala type-checker in every compilation unit where the annotated symbol is accessed.

Decidable Subtyping

The implementation of subtyping has been changed to prevent infinite recursions. Termination of subtyping is now ensured by a new restriction of class graphs to be finitary.

Case classes cannot be abstract

It is now explicitly ruled out that case classes can be abstract. The specification was silent on this point before, but did not explain how abstract case classes were treated. The Scala compiler allowed the idiom.

New syntax for self aliases and self types

It is now possible to give an explicit alias name and/or type for the self reference . For instance, in

the name is introduced as an alias for within and the self type of is assumed to be . This construct is introduced now in order to replace eventually both the qualified this construct and the clause in Scala.

Assignment Operators

It is now possible to combine operators with assignments. For example:

Changes in Version 2.3.2 (23-Jan-2007) {: #2.3.2 }

It is now possible to define patterns independently of case classes, using methods in extractor objects. Here is an example:

In the example, is an extractor object with two methods:

  • The method is used to build even numbers.
  • The method is used to decompose an even number; it is in a sense the reverse of . methods return option types: for a match that suceeds, for a match that fails. Pattern variables are returned as the elements of . If there are several variables, they are grouped in a tuple.

In the second-to-last line, ’s method is used to construct a number . In the last line, is tested against the pattern . This pattern succeeds for even numbers and assigns to the variable one half of the number that was tested. The pattern match makes use of the method of object . More details on extractors can be found in the paper Matching Objects with Patterns by Emir, Odersky and Williams

Tuples

A new lightweight syntax for tuples has been introduced. For any sequence of types T1 ,.., Tn,

T1 ,.., Tn is a shorthand for T1 ,.., Tn.

Analogously, for any sequence of expressions or patterns x1,.., xn,

x1 ,.., xn is a shorthand for x1 ,.., xn.

Infix operators of greater arities

It is now possible to use methods which have more than one parameter as infix operators. In this case, all method arguments are written as a normal parameter list in parentheses. Example:

Deprecated attribute

A new standard attribute is available. If a member definition is marked with this attribute, any reference to the member will cause a “deprecated” warning message to be emitted.

Changes in Version 2.3.0 (23-Nov-2006) {: #2.3.0 }

Procedures

A simplified syntax for functions returning has been introduced. Scala now allows the following shorthands:

for and

for .

Type Patterns

The syntax of types in patterns has been refined. Scala now distinguishes between type variables (starting with a lower case letter) and types as type arguments in patterns. Type variables are bound in the pattern. Other type arguments are, as in previous versions, erased. The Scala compiler will now issue an “” warning at places where type erasure might compromise type-safety.

Standard Types

The recommended names for the two bottom classes in Scala’s type hierarchy have changed as follows:

The old names are still available as type aliases.

Changes in Version 2.1.8 (23-Aug-2006) {: #2.1.8 }

Visibility Qualifier for protected

Protected members can now have a visibility qualifier, e.g., . In particular, one can now simulate package protected access as in Java writing

where would name the package containing .

Relaxation of Private Access

Private members of a class can now be referenced from the companion module of the class and vice versa.

Implicit Lookup

The lookup method for implicit definitions has been generalized. When searching for an implicit definition matching a type , now are considered

  • all identifiers accessible without prefix, and
  • all members of companion modules of classes associated with .

(The second clause is more general than before). Here, a class is associated with a type if it is referenced by some part of , or if it is a base class of some part of . For instance, to find implicit members corresponding to the type

one would now look in the companion modules (aka static parts) of , , , and . Before, it was just the static part of .

Tightened Pattern Match

A typed pattern match with a singleton type now tests whether the selector value is reference-equal to . For example:

This will match the second case and hence will print . Before, the singleton types were erased to , and therefore the first case would have matched, which is non-sensical.

Changes in Version 2.1.7 (19-Jul-2006) {: #2.1.7 }

Multi-Line string literals

It is now possible to write multi-line string-literals enclosed in triple quotes. Example

No escape substitutions except for unicode escapes are performed in such string literals.

Changes in Version 2.1.5 (24-May-2006) {: #2.1.5 }

Class Literals

There is a new syntax for class literals: For any class type , designates the run-time representation of .

Changes in Version 2.0 (12-Mar-2006) {: #2.0 }

Scala in its second version is different in some details from the first version of the language. There have been several additions and some old idioms are no longer supported. This section summarizes the main changes.

New Keywords

The following three words are now reserved; they cannot be used as identifiers

Newlines as Statement Separators

Newlines can now be used as statement separators in place of semicolons

Syntax Restrictions

There are some other situations where old constructs no longer work:

Pattern matching expressions

The keyword now appears only as infix operator between a selector expression and a number of cases, as in:

Variants such as or just are no longer supported.

in clauses

The idiom

is no longer supported. A connective is only allowed following an clause. For instance, the line above would have to be written

However, assuming is a trait , it is also legal to write

The latter expression is treated as equivalent to

where is the superclass of .

Regular Expression Patterns

The only form of regular expression pattern that is currently supported is a sequence pattern, which might end in a sequence wildcard . Example:

It is at current not clear whether this is a permanent restriction. We are evaluating the possibility of re-introducing full regular expression patterns in Scala.

Selftype Annotations

The recommended syntax of selftype annotations has changed.

becomes

That is, selftypes are now indicated by the new keyword. The old syntax is still available but is considered deprecated.

For-comprehensions

For-comprehensions now admit value and pattern definitions. For example:

Note the definition as the third item in the for-comprehension.

Conversions

The rules for implicit conversions of methods to functions have been tightened. Previously, a parameterized method used as a value was always implicitly converted to a function. This could lead to unexpected results when method arguments where forgotten. Consider for instance the statement below:

where is defined as follows:

Most likely, the programmer forgot to supply an empty argument list to . The previous Scala version would treat this code as a partially applied method, and expand it to:

As a result, the address of a closure would be printed instead of the value of .

Scala version 2.0 will apply a conversion from partially applied method to function value only if the expected type of the expression is indeed a function type. For instance, the conversion would not be applied in the code above because the expected type of ’s parameter is , not a function type.

The new convention disallows some previously legal code. Example:

The partial application of in the last line of the code above will not be converted to a function type. Instead, the compiler will produce an error message which states that arguments for method are missing. The problem can be fixed by providing an expected type for the partial application, for instance by annotating the definition of with its type:

On the other hand, Scala version 2.0 now automatically applies methods with empty parameter lists to argument lists when necessary. For instance, the expression above will now be expanded to

Scala version 2.0 also relaxes the rules of overriding with respect to empty parameter lists. The revised definition of matching members makes it now possible to override a method with an explicit, but empty parameter list with a parameterless method, and vice versa. For instance, the following class definition is now legal:

Previously this definition would have been rejected, because the method as inherited from takes an empty parameter list.

Class Parameters

A class parameter may now be prefixed by or .

Private Qualifiers

Previously, Scala had three levels of visibility: private, protected and public. There was no way to restrict accesses to members of the current package, as in Java. Scala 2 now defines access qualifiers that let one express this level of visibility, among others. In the definition

access to is restricted to all code within the class or package (which must contain the definition of )

Changes in the Mixin Model

The model which details mixin composition of classes has changed significantly. The main differences are:

  • We now distinguish between traits that are used as mixin classes and normal classes. The syntax of traits has been generalized from version 1.0, in that traits are now allowed to have mutable fields. However, as in version 1.0, traits may still do not have constructor parameters.
  • Member resolution and super accesses are now both defined in terms of a class linearization.
  • Scala’s notion of method overloading has been generalized; in particular, it is now possible to have overloaded variants of the same method in a subclass and in a superclass, or in several different mixins. This makes method overloading in Scala conceptually the same as in Java.

The new mixin model is explained in more detail in the Scala Language Specification.

Implicit Parameters

Views in Scala 1.0 have been replaced by the more general concept of implicit parameters

Flexible Typing of Pattern Matching

The new version of Scala implements more flexible typing rules when it comes to pattern matching over heterogeneous class hierarchies. A heterogeneous class hierarchy is one where subclasses inherit a common superclass with different parameter types. With the new rules in Scala version 2.0 one can perform pattern matches over such hierarchies with more precise typings that keep track of the information gained by comparing the types of a selector and a matching pattern. This gives Scala capabilities analogous to guarded algebraic data types.

I'm having trouble digging through Scala's (somewhat sparse?) documentation on the new 2.10 release. I have a situation where I am reading data recursively from a source without type information. On the time of reading I know the expected type, so I can check whether that type aligns with the incoming data.

My problem is: When attempting to retrieve a collection object with type parameters (for instance an ), how can I use the expected type to ensure that the read values are of the correct type?

So far I've fiddled around with code provided by the Scala Api that allows you to extract type-parameters. I also read about the Class Tags and how they can be used to create Arrays. So my next thought was to 1) find the type parameter, 2) create an array from that type and 3) see if the read data fits without exceptions, like so:

Since the above gives me the Type, it should be a simple matter of converting that type to a class tag. But the answer illudes me.

To be honest this solution seems a bit messy to me, but I haven't been able to figure out anything smarter. If there are alternative solutions I'm all ears!

Thanks in advance.

Edit: To clarify, my above example should demonstrate that I want to extract type X from Array[Int] (for example) and then make an instance of an array containing that particular type. Hope that made it clearer.

Edit: Perhaps further clarification is in order (did I really make it that unclear? :-) ). I want to read a collection from a data-source. And I want that collection to be typed with the correct, expected, type. So let's say I call the method . Since I know what type to expect I give it a type parameter of that expected type. As an example, let's say Array[Int]. It could be Array[String] or Iterable[Any] or simply Null or whatever. When the method is called, I would like to match the given, expected type (Array[Int]) to the type of the data read from the external source. If the found type is the same type - or a subtype - of the expected type we, can cast and return the data. If not, an exception is thrown, informing the user that the found data wasn't of the expected type. So to sum it up: How do I make a call to work?

Edit: I solved the issue by creating an Array[Any], retrieve the expected type (X above) and iterate the array to see if the elements are of the same type (or subtype) of X. If they are, we can safely cast to Array[X]. In the example below the expected type is represented by E. It's pretty hackish, I know, but again: I'd love to see alternatives...

scalareflectiontypescastingscala-2.10

Categories: 1

0 Replies to “Scala 2.10 Reflection Examples Essays”

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *