DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Event-Driven Fractals
  • Easily Update and Reload SSL for a Server and an HTTP Client
  • Writing a Chat With Akka
  • Snowflake Data Processing With Snowpark DataFrames

Trending

  • Application Integration for IoT Devices: A Detailed Guide To Unifying Your Ecosystem
  • Understanding Europe's Cyber Resilience Act and What It Means for You
  • TypeScript: Useful Features
  • Log Analysis: How to Digest 15 Billion Logs Per Day and Keep Big Queries Within 1 Second
  1. DZone
  2. Coding
  3. Languages
  4. Scala - Functions

Scala - Functions

Veeresham Kardas user avatar by
Veeresham Kardas
·
Mar. 12, 15 · Interview
Like (0)
Save
Tweet
Share
1.33K Views

Join the DZone community and get the full member experience.

Join For Free

As we know functions are group of statements to perform a piece of operation/task. We will quickly dive into the details instead of long definitions.

Syntax

def is the keyword used to define the function.

def function_name ( {,param2:type}):returnType = { [Statements] return value; }

Example

def sum(x:Int, y:Int) : Int =
{
   return x + y;
}

// Calling the function
val x:Int = 20;
val y:Int = 30;
var z:Int = sum(x,y);

This exactly looks the way we define and call in other languages but Scala simplified the definition by making some of the tokens optional.

  • Type of the return value is optional. So function prototype can be without :returnType after arguments
  • return keyword is optional.
  • If there is only one line in the function, then braces are options. Braces required to say it's a block

Now, the above function can be defined as

def sum(x:Int, y:Int) = x + y;

Anonymous Functions

Scala provides a very simple and convenient way to define the anonymous functions. See below for an example

val sum = (x:Int, y:Int) => x + y; // val to be used instead of def keyword.

//Calling
println(sum(15,50)); //Prints 65
  • In case of anonymous functions, we don't need def keyword. We have to use val keyword instead.
  • Calling the function is same as the normal functions.

One more point here is, the parameter names are optional in case of anonymous functions. So, we can define the function as

val add5:(Int,Int)=> Int = _ + _; // No argument names

//Call the function
println(sum(15,50)); //calling is same.

Return Tuples 

Scala allows us to return multiple values as a tuple. Let's see an example of how to swap two strings using a tuple.

def swap(x:String, y:String):(String, String) = { return (y, x)}; //Returning in reverse order 
def swap2(x:String, y:String) = (y, x); //Removed optional tokens

//Calling
val (a,b) = swap("Hi","Scala");
println(a,b); //Prints Scala, Hi

val (c,d) = swap2("Hi","Scala");
println(c,d); //Prints Scala, Hi

Variable arguments 

Variable arguments can be specified to function using the operator *. Example shows the syntax and usage.

def printArgs(x:String*) = {
  for(a <- x)
  {
     println(a);
  }
}

//Calling
printArgs("Hi", "Hello", "Scala"); //Prints the strings in order.

Default and Named arguments 

Scala allows to default some of the arguments and also to pass the arguments based on the name of the parameters instead of the order

def increment(x:Int, y:Int = 1) = x + y; // Defaults the argument y to 1 if not passed

//Calling
println(increment(20)); //Increases by 1 because not passed
println(increment(20,5)); //Increases by 5 because 5 is passed

def printValues(x:String, y:Int) = {
   println(" X = "+x+" : Y = "+y);
}

//Calling
printValues(x="Hi", y=20); // Prints X = Hi : Y = 20
printValues(y=20, x="Hi"); // Prints X = Hi : Y = 20 - Even order is different because of named arguments

That's it for the current post. For more posts, please visit my blog.  Happy Learning!!!

Scala (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Event-Driven Fractals
  • Easily Update and Reload SSL for a Server and an HTTP Client
  • Writing a Chat With Akka
  • Snowflake Data Processing With Snowpark DataFrames

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: