Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
Program to convert Java Set of strings to a Traversable in Scala
Next article icon

Scala Trait Traversable | Set-1

Last Updated : 12 Apr, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

Introduction:
A root trait of the entire class of the Scala collections is Trait Traversable. It is available at the uppermost position of the collection hierarchy. It has uniquely one abstract operation, which is foreach. Here each of the operations are assured to be executed in a single-threaded approach.
Syntax:

def foreach[U](f: Elem => U)

Here, the operation f is concerned with all the elements of the collection and Elem => U is the type of operation, where “Elem” is the type of elements in the Scala’s collection and “U” is an inconsistent result type.

Some Important points:

  • Traversable is accomplished by the Scala’s Collection classes.
  • It is obligatory for Traversable to define foreach method only, as Traversable can inherit all the other methods.
  • The foreach method could traverse all the elements of the Scala’s collection class.
  • There are numerous concrete methods which are defined by Traversables.
  • List, Array, Map, Set, and many more are the subclass of Traversables.
Operations performed by the Class Traversable are as follows:
  1. Abstract Method:
    The only abstract method here is foreach, which can traverse over all the elements of the Collection.
    Example :




    //Scala program of abstract method
      
    //Creating object 
    object CS 
    {
        //Main method
        def main(args: Array[String]) 
        {
            //Creating an Array of elements
            val x = Array("GEEKS", "FOR", "GEEKS")
      
            //Calling foreach method
            x.foreach { E =>
            val y = E.toLowerCase
      
            //Display strings
            println(y)
            }
        }
    }
     
     
    Output:
      geeks  for  geeks  

    Here, all the elements of the Array stated above are traversed by foreach method and then they are converted from uppercase to lowercase.
    Example:




    // Scala program of abstract method
      
    // Creating object 
    object GFG
    {
        // Main method
        def main(args: Array[String]) 
        {
            //Creating list of numbers
            val l = List(2, 6, 8, 7, 10, 11, 13)
      
            //Calling foreach and displaying
            //numbers of list after 
            //multiplication each of them
            l.foreach(n => println(n * 6))
        }
    }
     
     
    Output:
      12  36  48  42  60  66  78  

    Here, foreach method traverses all the numbers of the list and multiplies each of them.

  2. Addition operation:
    Here, Addition operation i.e, ++ adds two Traversables together or adds each of the elements of an iterator to a Traversable.
    Example:




    // Scala program of addition operation
      
    // Creating object 
    object GFG
    {
        // Main method
        def main(args: Array[String]) 
        {
            // Creating set of numbers
            val x = Set(7, 8, 9, 10)
      
            // Creating list of numbers
            val y = List(1, 5, 8, 18)
      
            //performing addition operation
            val s1 = x ++ y
            val s2 = y ++ x
      
            //Displaying set
            println(s1)
      
            //Displaying list 
            println(s2)
        }
    }
     
     
    Output:
      Set(5, 10, 1, 9, 7, 18, 8)  List(1, 5, 8, 18, 7, 8, 9, 10)  

    Here, when a Set is added to a List then a Set is generated and when a List is added to a Set then a List is generated.

  3. Map operations:
    The three Map operations are map, flatMap, and collect.
    These Map operations create a new collection by assigning a few function to the elements of Scala collection.
    Example :




    // Scala program of Map operations
      
    // Creating object 
    object GFG
    {
      
        // Main method
        def main(args: Array[String]) 
        {
      
            // Creating Set of numbers
            val x = Set(8, 9, 5, 10)
      
            // Applying map operation
            val y = x.map(_ * 9)
      
            // Displaying Set 
            println(y)
        }
    }
     
     
    Output:
      Set(72, 81, 45, 90)  

    Here, the Map operation (i.e, map) will assign the stated function on each elements of a Traversable and will return a new collection as output.
    Example :




    // Scala program of Map operations
      
    // Creating object 
    object GFG
    {
      
        // Main method
        def main(args: Array[String]) 
        {
      
            // Creating a List of lists
            val q = List(List(7), List(8, 9, 10), List(11, 12, 13))
      
            // Applying map operation
            val r = q.flatMap(_.map(_ + 3))
      
            // Displaying List
            println(r)
        }
    }
     
     
    Output:
      List(10, 11, 12, 13, 14, 15, 16)  

    Here, the flatMap will assign the stated function on each elements within the elements and then will Concatenate the output.
    Example :




    // Scala program of Map operations
      
    // Creating object 
    object GFG
    {
      
        // Main method
        def main(args: Array[String]) 
        {
      
            // Creating List of numbers
            val x = List(9, 3, 5, 11, 15, 4)
      
            // Applying map operation 
            val y = x.collect 
            {
      
                // Partial function
                case z : Int if (z % 3 == 0) => z + 2
            }
      
            //Displaying list
            println(y)
        }
    }
     
     
    Output:
      List(11, 5, 17)  

    Here, collect will assign a partial function to each elements of Traversable and will give a non-identical collection as output.



Next Article
Program to convert Java Set of strings to a Traversable in Scala
author
nidhi1352singh
Improve
Article Tags :
  • Scala
  • Scala

Similar Reads

  • Scala Trait Traversable | Set-2
    prerequisite- Scala Trait Traversable | Set-1In the previous Set we have seen some of the operations performed by the Class Taversable. Now, in this Set we will perceive some more operations. These operations are as follows: Conversion operations: The Conversion operations are toList, toSeq, toArray
    8 min read
  • Program to convert Java Set to a Traversable in Scala
    A java Set can be converted to a Traversable collection in Scala by utilizing toTraversable method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Example:1# // Scal
    2 min read
  • Set in Scala | Set-1
    A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request. Syntax: // Immutable set val variable_name: Set[type] = Set(item1, item2, ite
    3 min read
  • Program to convert Java Set of strings to a Traversable in Scala
    A java Set of strings can be converted to a Traversable collection in Scala by utilizing toTraversable method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Example
    2 min read
  • Program to convert Java Set of bytes to a Traversable in Scala
    A java Set of bytes can be converted to a Traversable collection in Scala by utilizing toTraversable method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Example:1
    1 min read
  • Set in Scala | Set-2
    Prerequisite: Set in Scala | Set-1Adding items in Mutable SetIn Set, We can only add new elements in mutable set. +=, ++== and add() method is used to add new elements when we are working with mutable set in mutable collection and += is used to add new elements when we are working with mutable set i
    7 min read
  • Program to convert Java Set of doubles to a Traversable in Scala
    A java Set of doubles can be converted to a Traversable collection in Scala by utilizing toTraversable method of Java in Scala. Here, you need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Exampl
    1 min read
  • Program to convert Java Set of Shorts to a Traversable in Scala
    A java Set of Shorts can be converted to a Traversable collection in Scala by utilizing toTraversable method of Java in Scala. Here, you need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Example
    1 min read
  • Program to convert Java Set of floats to a Traversable in Scala
    A java Set of floats can be converted to a Traversable collection in Scala by utilizing toTraversable method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Example:
    1 min read
  • Program to convert Java list to Traversable in Scala
    A java list can be converted to a Traversable collection in Scala by utilizing toTraversable method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in d
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences