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:
Scala Type Hierarchy
Next article icon

Scala | Type Inference

Last Updated : 04 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Scala Type Inference makes it optional to specify the type of variable provided that type mismatch is handled. With type inference capabilities, we can spend less time having to write out things compiler already knows. The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly. Let us first have a look at the syntax of how immutable variables are declared in scala.

val variable_name : Scala_data_type = value

Example: 

Scala
// Scala program of type interference object Geeks  {         // Main method      def main(args: Array[String])      {          // prints a double value         val a : Double = 7.893         println(a)           println(a.getClass)              }  }  

Output : 

7.893 double

In above example the getClass method is used to print the type of the variable to the console. For the above example the type of variable 'a' is double. However, through type inference, Scala automatically detects the type of the variable without explicitly specified by the user. Example : 

Scala
// Scala program of type interference object Geeks {       // Main method      def main(args: Array[String])      {          // type inference         println("Scala Data Types")         val number = 5         val big_number = 100000000L         val small_number = 1         val double_number = 2.50         val float_number = 2.50f         val string_of_characters = "This is a string of characters"         val byte = 0xc         val character = 'D'         val empty = ()                  println(number)         println(big_number)         println(small_number)         println(double_number)         println(float_number)         println(string_of_characters)         println(byte)         println(character)         println(empty)              }  }  

Output : 

Scala Data Types 5 100000000 1 2.5 2.5 This is a string of characters 12 D ()

Note that no data type is specified explicitly for the above variables. Scala Type Inference For Functions Now we will have a look at how type inference works for functions in Scala. Let's first have a look at how functions are declared in Scala. Syntax:

 def function_name ([parameter_list]) : [return_type] = {       // function body  }

Example : 

Scala
// Scala program of multiply two numbers object Geeks  {       // Main method      def main(args: Array[String])     {                   // Calling the function          println("Product of the two numbers is: " + Prod(5, 3));      }                // declaration and definition of Product function      def Prod(x:Int, y:Int) : Int =     {          return x*y      }  }  

Output :

Product of the two numbers is: 15

In above example as we can from the declaration that the specified return type is Int. With Scala type inference, Scala automatically detects the type of the function without explicitly specified by the user. Example : 

Scala
// Scala program of type interference object Geeks  {       def factorial(n: Int)= {                   var f = 1         for(i <- 1 to n)          {              f = f * i;          }                   f      }       // Driver Code      def main(args: Array[String])      {          println(factorial(5))      }  } 

Output : 

120
def factorial(n: Int)= 

In above example colon and the return type are omitted. Also, In above example, we have omitted the statement "return f" to "f" as we have not specified the return type. If instead of "f", "return f" was placed then the following error is shown by the compiler.

prog.scala:11: error: method factorial has return statement; needs result type         return f         ^

This shows the power of the Scala type inference, but for recursive methods, the compiler is not able to infer a result type. The above factorial function can also be implemented recursively. The following is a recursive definition of the factorial function with no type inference. Example : 

Scala
// Scala program of using recursion object Geeks {       // factorial function     def factorial(n: Int): Int =     {          if (n == 0)              return 1         else             return n * factorial(n-1)      }       // Driver Code      def main(args: Array[String])      {          println(factorial(5))      }   } 

Output : 

120

Example : With Scala type inference 

Scala
// Scala program of type interference object Geeks  {           // Defining function with type interference     def factorial(n: Int) =     {          if (n == 0)              1         else             n * factorial(n-1)      }       // Driver Code      def main(args: Array[String])      {          println(factorial(5))      }   } 

Output:

Compile Errors : prog.scala:8: error: recursive method factorial needs result type             n * factorial(n-1)                 ^

Next Article
Scala Type Hierarchy

D

dahalegopal27
Improve
Article Tags :
  • Scala
  • Scala
  • Scala-Data Type

Similar Reads

  • Scala AnyRef type
    The Scala kind hierarchy starts with Any, that's the supertype of all types. The direct subclasses of Any are AnyVal and AnyRef. Whereas AnyVal represents price kinds (which includes Int, Double, and so on.), AnyRef represents reference types. AnyRef serves because the fundamental type and root deta
    3 min read
  • Scala Type Hierarchy
    There are no primitive types in Scala(unlike Java). All data types in Scala are objects that have methods to operate on their data. All of Scala's types exist as part of a type hierarchy. Every class that we define in Scala will also belong to this hierarchy automatically. AnyAny is the superclass o
    3 min read
  • Scala Any type
    In Scala, the Any class is at the top of the hierarchy of classes. Scala stands like the supertype of all types and provides a foundation for Scala's type system. Any is like a supertype from which all values in scala are inherited whether it is a value type like(Int, Double, Float, etc.) or a refer
    7 min read
  • Type Casting in Scala
    A Type casting is basically a conversion from one type to another. In Dynamic Programming Languages like Scala, it often becomes necessary to cast from type to another.Type Casting in Scala is done using the asInstanceOf[] method. Applications of asInstanceof methodThis perspective is required in ma
    4 min read
  • Higher-Kinded Types in Scala
    This article focuses on discussing Higher-Kinded types in Scala. What is the Higher-Kinded Type? A higher-kinded type is a type that can stand for other types, which themselves stand for more types. It's a way to talk about types that are built from other types. They let us write code that can handl
    4 min read
  • Scala Path Dependent Type
    Scala Path Dependent Types (PDTs) are an advanced feature of the Scala language that allows users to create types that are dependent on the path in which they are accessed. The type of a variable or object is not determined by its own structure or characteristics, but rather by the path in which it
    4 min read
  • Data Types in Scala
    A data type is a categorization of data which tells the compiler that which type of value a variable has. For example, if a variable has an int data type, then it holds numeric value. In Scala, the data types are similar to Java in terms of length and storage. In Scala, data types are treated same o
    3 min read
  • How to Overcome Type Erasure in Scala?
    Type erasure may provide challenges in Scala, particularly when dealing with generics. Type tags and manifests are a means to prevent type erasure. By preserving type information during runtime, these approaches let you operate with genuine types as opposed to erased types. Table of Content What is
    3 min read
  • Scala | Tuple
    Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value. val name = (15, "Chandan", tr
    5 min read
  • What is Lifting in Scala?
    Scala is a programming language that is expressive and effective. It permits builders to produce code that is both elegant and succinct. Lifting is one such belonging that is vital to useful programming paradigms. Functions may fit easily on values interior containers, such as Option, List, Future,
    3 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