The Wayback Machine - https://web.archive.org/web/20240927181458/https://www.geeksforgeeks.org/scala-trait-mixins/
Open In App

Scala | Trait Mixins

Last Updated : 15 Apr, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We can extend several number of scala traits with a class or an abstract class that is known to be trait Mixins. It is worth knowing that only traits or blend of traits and class or blend of traits and abstract class can be extended by us. It is even compulsory here to maintain the sequence of trait Mixins or else the compiler will throw an error.
Note:

  1. The Mixins traits are utilized in composing a class.
  2. A Class can hardly have a single super-class, but it can have numerous trait Mixins. The super-class and the trait Mixins might have identical super-types.

Now, lets see some examples.

  • Extending abstract class with trait
    Example :




    // Scala program of trait Mixins
      
    // Trait structure
    trait Display
    { 
      
        def Display() 
    } 
      
    // An abstract class structure
    abstract class Show
    { 
        def Show() 
    } 
      
    // Extending abstract class with
    // trait
    class CS extends Show with Display
    {
          
        // Defining abstract class
        // method
        def Display()
        {     
            // Displays output
            println("GeeksforGeeks") 
        } 
          
        // Defining trait method
        def Show()
        {                                     
            // Displays output 
            println("CS_portal") 
        } 
    }
      
    // Creating object
    object GfG
    { 
        // Main method
        def main(args:Array[String])
        { 
              
            // Creating object of class CS
            val x = new CS() 
              
            // Calling abstract method
            x.Display() 
              
            // Calling trait method
            x.Show() 
        } 
    } 

    
    

    Output:

    GeeksforGeeks
    CS_portal
    

    Here, the correct order of Mixins is that, we need to extend any class or abstract class first and then extend any trait by using a keyword with.

  • Extending abstract class without trait
    Example :




    // Scala program of trait Mixins
      
    // Trait structure
    trait Text
    { 
        def txt() 
    }
      
    // An abstract class structure
    abstract class LowerCase
    { 
        def lowerCase() 
    } 
      
    // Extending abstract class 
    // without trait
    class Myclass extends LowerCase
    {
          
        // Defining abstract class
        // method
        def lowerCase()
        { 
            val y = "GEEKSFORGEEKS"
              
            // Displays output
            println(y.toLowerCase()) 
        } 
          
        // Defining trait method
        def txt()
        {                                     
          
            // Displays output 
            println("I like GeeksforGeeks") 
        } 
    } 
      
    // Creating object
    object GfG
    { 
        // Main method
        def main(args:Array[String])
        { 
              
            // Creating object of 'Myclass'
            // with trait 'Text'
            val x = new Myclass() with Text
              
            // Calling abstract method
            x.lowerCase() 
              
            // Calling trait method
            x.txt() 
        } 
    } 

    
    

    Output:

    geeksforgeeks
    I like GeeksforGeeks
    

    Thus, from this example we can say that the trait can even be extended while creating object.
    Note: If we extend a trait first and then the abstract class then the compiler will throw an error, as that is not the correct order of trait Mixins.



Previous Article
Next Article

Similar Reads

Scala | Sealed Trait
Sealed provides exhaustive checking for our application. Exhaustive checking allows to check that all members of a sealed trait must be declared in the same file as of the source file. That means that all the possible known members of a trait that must be included are known by the compiler in advance. So this gives us advantage to prevent mistakes
4 min read
Scala Trait Traversable | Set-1
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) H
4 min read
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, toStream, toSet, toMap, toIterable, and toIndexe
8 min read
Scala Trait Traversable | Set-3
Prerequisite : Scala Trait Traversable | Set-1 Scala Trait Traversable | Set-2 It is recommended to see (Set-1, Set-2) before this Set. The operations are as follows: Sub-Collection retrieval operations: The operations here are slice, drop, dropWhile, filter, filterNot, tail, take, takeWhile, and init. These operations are utilized to return some s
8 min read
Scala Trait Traversable | Set-4
Prerequisite :- Scala Trait Traversable | Set-1 Scala Trait Traversable | Set-2 Scala Trait Traversable | Set-3 It is recommended to view Set-1, Set2 and Set-3 before this one. The operations are as follows: Folds: The operations here are reduceRight, reduceLeft, /: or foldLeft, :\ or foldRight. This methods apply binary operation to the successive
6 min read
Scala | Trait App
App is a trait which is utilized to rapidly change objects into feasible programs, which is carried out by applying DelayedInit function and the objects inheriting the trait App uses this function to execute the entire body of the program as a section of an inherited main method. Note: trait App extends DelayedInit The Linear Super-types here are:
2 min read
Trait Linearization in Scala
Scala Linearization is a deterministic process which comes into play when an object of a class is created which is defined using inheritance of different traits and classes. linearization helps to resolve the diamond problem which occurs when a class or trait inherits a same property from 2 different concrete classes or traits. Syntax : trait C{} t
5 min read
Scala short <(x: Short): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The <(x: Short) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def <(x: Short): Boolean Return Type: It returns true if this value is less than x, otherwise false. Example #1: // Scala p
1 min read
Scala short <(x: Char): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The <(x: Char) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def <(x: Char): BooleanReturn Type: It returns true if this value is less than x, otherwise false. Example #1: C/C++ Code //
1 min read
Scala Extractors
In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and constructs an object so, it's helpful in constructing
6 min read
Scala | Partially Applied functions
The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required. we call a function we can pass less arguments in it and when we pass less arguments it does not throw an ex
3 min read
Scala String indexOf(String str) method with example
The indexOf(String str) method is utilized to return the index of the sub-string which occurs first in the string stated. Method Definition: indexOf(String str) Return Type: It returns the index of the sub-string which is specified in the argument of the method. Example #1: // Scala program of int indexOf() // method // Creating object object GfG {
1 min read
Scala String contentEquals() method with example
The contentEquals() method is utilized to compare a string to the content of StringBuffer. Method Definition: Boolean contentEquals(StringBuffer sb) Return Type: It returns true if the content is equal to the stated string else it returns false. Example #1: // Scala program of contentEquals() // method // Creating object object GfG { // Main method
1 min read
Scala Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // Scala Program to illustrate the keywords // Here object, def, and var are valid ke
2 min read
Scala Int /(x: Int) method with example
The /(x: Int) method is utilized to return the quotient when the specified first int value is divided by the second int value. Method Definition: (First_Int_Value)./(Second_Int_Value) Return Type: It returns the quotient when the specified first int value is divided by the second int value. Example #1: // Scala program of Int /(x: Int) // method //
1 min read
Scala Int /(x: Short) method with example
The /(x: Short) method is utilized to return the quotient when the specified int value is divided by the short value. Method Definition: (Int_Value)./(Short_Value) Return Type: It returns the quotient when the specified int value is divided by the short value. Example #1: // Scala program of Int /(x: Short) // method // Creating object object GfG {
1 min read
Program to print Java Set of characters in Scala
A java Set of characters can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples. Example:1# // Scala program to print Java Set // of characters in Scala // Creating object object
2 min read
How to Install Scala IDE For Eclipse?
In this tutorial, we'll look at how to set up the Eclipse IDE for Scala. This tutorial is for those who are new to Scala. Requirement for InstallationEclipse (Install link) if you don't know how to install Eclipse then refer to this article.JDK 11 (you may use JDK 6 onwards) Note: If you do not have JDK installed, you may get them from this link. I
2 min read
Scala Map size() method with example
The size() is utilized to find the number of key-value pairs in the stated map. Method Definition: def size: Int Return Type: It returns the number of elements in the map. Example #1: // Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks
1 min read
Scala SortedMap addString() method with a start, a separator and an end with example
This method is same as addString() method but here a start, a separator and an end is also included. Method Definition: def addString(sb: mutable.StringBuilder, start: String, sep: String, end: String): mutable.StringBuilder Where, sep is the separator stated. Return Type: It returns the elements of the SortedMap in the String Builder and a start,
2 min read
Scala Iterator addString() method with example
The addString() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class IterableOnceOps. It is utilized to append the elements of the Scala Iterator to a String Builder. Method Definition : def addString(b: StringBuilder): StringBuilder Return Type : It returns the String Builder to which the elements
1 min read
Scala String substring(int beginIndex, int endIndex) method with example
The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified. Method Definition: String substring(int beginIndex, int endIndex) Return Type: It returns string which is the part of the stated String. Note: It is same as sub-sequence method but the only dif
1 min read
Scala | Functions Call-by-Name
In Scala when arguments pass through call-by-value function it compute the passed-in expression's or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expression's value every time it get accessed inside the function. Here example are shown with difference and sy
3 min read
Program to convert Java list to an iterator in Scala
A java list can be converted to an iterator in Scala by utilizing toIterator 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 details. Example:1# C/C++ Code // Scala program to convert Java lis
3 min read
Scala Set &() method with example
The &() method is utilized to create a new set consisting of all elements that are present in both the given sets. Method Definition: Return Type: It returns a new set consisting of all elements that are present in both the given sets. Example #1: // Scala program of &() // method // Creating object object GfG { // Main method def main(args
1 min read
Scala | Type Inference
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
4 min read
Program to convert Java set of Shorts to an Indexed Sequence in Scala
A java set of Shorts can be converted to an Indexed Sequence in Scala by utilizing toIndexedSeq 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 details. Example:1# // Scala program to convert
2 min read
Scala Int <(x: Char) method with example
The <(x: Char) method is utilized to return true if the specified int value is less than the char value, otherwise returns false. Here the char value is the ASCII value of the specified char. Method Definition: (Int_Value).<(Char_Value)Return Type: It returns true if the specified int value is less than the char value, otherwise returns false
1 min read
Scala Int <=(x: Double) method with example
The <=(x: Double) method is utilized to return true if the specified int value is less than or equal to the double value, otherwise returns false. Method Definition: (Int_Value).<=(Double_Value) Return Type: It returns true if the specified int value is less than or equal to the double value, otherwise returns false. Example #1: // Scala prog
1 min read
Scala Int <=(x: Byte) method with example
The <=(x: Byte) method is utilized to return true if the specified int value is less than or equal to the byte value, otherwise returns false. Method Definition: (Int_Value).<=(Byte_Value) Return Type: It returns true if the specified int value is less than or equal to the byte value, otherwise returns false. Example #1: // Scala program of I
1 min read
Article Tags :