Constructor Function: Scala - DZone Java [PDF]

May 24, 2016 - Given that Scala is a functional language (object/functional, really), building a Constructor Function in

2 downloads 19 Views 315KB Size

Recommend Stories


Manualul inginerului constructor pdf
Courage doesn't always roar. Sometimes courage is the quiet voice at the end of the day saying, "I will

PdF Scala Cookbook
And you? When will you begin that long journey into yourself? Rumi

Scala Sockelleisten Scala Skirts
You often feel tired, not because you've done too much, but because you've done too little of what sparks

Code Cube Constructor
So many books, so little time. Frank Zappa

Kirill Lebedev, PhD, Full Stack Java and Scala developer
You miss 100% of the shots you don’t take. Wayne Gretzky

Beaufort Scala
Come let us be friends for once. Let us make life easy on us. Let us be loved ones and lovers. The earth

[PDF] Building Java Programs
Ego says, "Once everything falls into place, I'll feel peace." Spirit says "Find your peace, and then

pdf - Programmierkurs Java
Stop acting so small. You are the universe in ecstatic motion. Rumi

pdf - Programmierkurs Java
Keep your face always toward the sunshine - and shadows will fall behind you. Walt Whitman

[PDF] Building Java Programs
Learn to light a candle in the darkest moments of someone’s life. Be the light that helps others see; i

Idea Transcript


Constructor Function: Scala Given that Scala is a functional language (object/functional, really), building a Constructor Function in Scala is actually pretty straightforward. by Ted Neward

· May. 24, 16 · Java Zone · Tutorial

Join the DZone community and get the full member experience. JOIN FOR FREE Learn how to stop testing everything every sprint and only test the code you’ve changed. Brought to you by Parasoft. Given that Scala is a functional language (object/functional, really), building a Constructor Function in Scala is actually pretty straightforward.

Object Method Constructor Scala allows us to create per-class methods on the class object, providing a convenient place on which to store methods designed to construct instances of the class. Scala traits are used to define the Interface, so as to better take advantage of the statically-typed nature of the compiler and provide compilation guarantees. In addition, because Scala supports nested classes (meaning, in this particular case, classes whose definition appears entirely inside a function definition), we can “hide” the implementation in much the same way that Java uses inner-class implementations, though we still do need to provide a name to the type. trait Interface { def operation(adjust: Int) : Int; } object Implementation { def construct(startingValue : Int) : Interface = { class Impl(var current : Int) extends Interface { def operation(adjust: Int) : Int = { current += adjust return current } } return new Impl(startingValue) } } object App { def main(args : Array[String]) = { val intf = Implementation.construct(100) System.out.println(intf.operation(10)) } }

However, it can make more sense to hide the implementation entirely, and because Scala allows for both traits and class object definitions, we can define Interface to be both trait and class object. While at it, we can define the Interface class object to appear as a function object by defining the “construct” method as the function application method (“apply”) instead as well: trait Interface { def operation(adjust: Int) : Int; } object Interface { def apply(startingValue : Int) : Interface = { class Impl(var current : Int) extends Interface { def operation(adjust: Int) : Int = { current += adjust return current } } return new Impl(startingValue) } } object App { def main(args : Array[String]) = { val intf = Interface(100) System.out.println(intf.operation(10)) } }

This then looks like the Constructor Function from other functional languages. Because Scala is an object/functional hybrid language, it’s relatively easy to use Closure-based State to hold the state outside of the actual object returned.

Runtime Replacement However, the disadvantage to the above is that the Constructor Function cannot be replaced at run time, since it is statically defined as part of the class. Adjusting for this as a desired consequence is actually relatively simple in the Scala case: the Constructor Function is either captured as a lambda and used directly, or else hidden behind the construction method, depending on what the exact desired client construction semantics are: trait Interface { def operation(adjust: Int) : Int; } object Interface { var constructorFn = construct _ def apply(startingValue: Int) : Interface = constructorFn(startingValue) def construct(startingValue : Int) : Interface = { class Impl(var current : Int) extends Interface { def operation(adjust: Int) : Int = { current += adjust return current } } return new Impl(startingValue) } } object App { def main(args : Array[String]) = { val intf = Interface(100) System.out.println(intf.operation(10)) Interface.constructorFn = { startingValue => class Impl(var current : Int) extends Interface { def operation(adjust: Int) : Int = { current += adjust * 2 return current } } new Impl(startingValue) } val intf2 = Interface(100) System.out.println(intf2.operation(10)) } }

Note the syntax for capturing the “construct” method inside of the Interface class object—Scala requires the use of the underscore to signify that we want to capture the function as a value, rather than invoke it. (The error message here can be a bit cryptic the first time you see it.)

Parameterized Construction Scala uses type parameterized Constructor Functions throughout the runtime library to simplify the construction of several of its collection classes. For example, constructing a Map uses the class object’s “apply” and the types passed in to determine what time of map to return: Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_20). Type in expressions for evaluation. Or try :help. scala> val capitals = Map("Tacoma" -> "WA") capitals: scala.collection.immutable.Map[String,String] = Map(Tacoma -> WA) scala> val pops = Map("Seattle" -> 5000000) pops: scala.collection.immutable.Map[String,Int] = Map(Seattle -> 5000000)

Here, the Map will obtain its key/value types out of the respective types of the pair (constructed using the “->” operator) passed in. Syntactically, the client need not be aware of the actual types (or even the syntax) of the Map.

Get the top tips for Java developers and best practices to overcome common challenges. Brought to you by Parasoft.

Like This Article? Read More From DZone Leaving Unhandled Errors Behind

Scala vs. Java for Big Data Engineering

New Language Features on the JVM

Free DZone Refcard

Topics: SCALA , JAVA , JVM , PATTERNS

Published at DZone with permission of Ted Neward , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own.

Java Partner Resources Get Unit Testing Done Right: Top Tips for Java Developers Parasoft Predictive Analytics + Big Data Quality: A Love Story Melissa Data Get Started with Spring Security 5.0 and OpenID Connect (OIDC) Okta Microservices for Java Developers: A Hands-On Introduction to Frameworks & Containers Red Hat Developer Program

Getting Started With Kotlin

Smile Life

When life gives you a hundred reasons to cry, show life that you have a thousand reasons to smile

Get in touch

© Copyright 2015 - 2024 PDFFOX.COM - All rights reserved.