Trending November 2023 # How Does Case Classwork In Scala With Examples? # Suggested December 2023 # Top 15 Popular

You are reading the article How Does Case Classwork In Scala With Examples? updated in November 2023 on the website Minhminhbmm.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested December 2023 How Does Case Classwork In Scala With Examples?

Introduction to Scala Case Class

Case classes in scala can be defined by using the case keyword. This class is a normal class like any other class in scala, but these classes are immutable, meaning we cannot change their value once assigned. Also, case classes in scala do not require a new keyword to create an object of the class; they have a default method called apply(), which takes care of object creation. Case class in scala is used in pattern matching.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

While defining a case class, we just require a case keyword followed by the name of our class and a list of parameters; if any, otherwise, it can be empty as well. Also, we can have one practice example of the syntax for beginners to understand.

Case class class_name_here(list_of_parameter)

Example:

Case class Demo(name:String)

Here we have defined a case class with a name demo and passing one parameter inside the bracket. This parameter list can also be empty if not required; it totally depends upon the requirement.

How does Case Classwork in Scala?

Case class in scala uses apply method, which manages the creation of objects; we do not need to use a new keyword while using the case class. Also, for the comparison of the object, this class uses the equals method, and this class is immutable in nature; also, the parameter that we used inside this class is by default public. They are mainly used with pattern matching in scala.

Now let’s have a look at creating the object for the case class;

Example:

case class Demo(id: Int) val demo_var = Demo(100)

In the above lines of code, we have one case class defined as Demo, and in the next line, we are trying to use the case class by creating its object and assigning a value for the variable. But we have not used a new keyword here to instantiate it. So now, let’s see one syntax to use the parameter of the case class in scala.

Example:

case class Demo(id: Int, name: String, age: Int) val case_var = Demo(200, "test case", "30") println(case_var.name)

The above lines of code will work and print the corresponding name in the console as output. But if we try to reassign the parameter of the case class, then it is not possible also; all the parameters are public by default. Let’s try to reassign it; see below;

Example:

case_var.name = "this will not work."

Example:

case class Demo(id: Int, name: String, age: Int) val case_var1 = Demo(200, "test case", "30") val case_var2 = Demo(200, "test case", "30") val result = case_var1 == case_var2

In the above lines of code, we have created two case objects. Both are the same in structure as well as in value. So in the case of class in scala, it will compare the structure of the object rather than its reference. So the output for the above lines of code will be true. Also, we can create a copy of the object for this it provides us with a copy() method, but it will create one shallow copy of the instance. So let’s see one example of how we can achieve it in code.

Example:

case class Demo(id: Int, name: String, age: Int) val case_var1 = Demo(200, "test case", "30") val case_var2 = case_var1.copy(id = case_var1.id, name = case_var1.name, age = case_var1.age) printn(case_var2)

In this example, we are creating two objects, but the second object is the copy of the first object. Therefore, we are using the copy() method to create a shallow copy of the case object.

We also have a case object when and these terms are used interchangeably often. Let’s discuss some important points related to class/ object, which are mentioned below;

The class which does not contain any parameter into it then that case class is referred to as an object.

Scala case objects are the same as the other objects in scala, but they are the combination of case class and case object.

Case object contains more features and attributes than other objects in the scala.

Case objects are serializable, and they have by default implementation for the hashcode method in it.

Examples of Scala Case

Different examples are mentioned below:

Example #1

A simple example for beginners to see how to deal with case class and print the details.

case class Student (id:Int, name:String, age:Int, city: String) object Main { def main(args: Array[String]) { var s1 = Student(001, "Amit verma", 20, "Mumbai") var s2 = Student(002, "Sumit sharma", 15, "Delhi") var s3 = Student(003, "Vihit verma", 18, "Pune") var s4 = Student(004, "Nimit shah", 20, "Bihar") println("detail of first student ::") println( "is di :: " + chúng tôi + " name is :: " + chúng tôi + " age is :: " + chúng tôi + " city is :: " + s1.city) println("detail of second student ::") println("is di :: " + chúng tôi + " name is :: " + chúng tôi + " age is :: " + chúng tôi + " city is :: " + s2.city) println("detail of third student ::") println("is di :: " + chúng tôi + " name is :: " + chúng tôi + " age is :: " + chúng tôi + " city is :: " + s3.city) println("detail of fourth student ::") println("is di :: " + chúng tôi + " name is :: " + chúng tôi + " age is :: " + chúng tôi + " city is :: " + s4.city) } }

Output:

Example #2

Checking if the objects defined are equal or not in the case.

Code:

case class Student (id:Int, name:String, age:Int, city: String) object Main { def main(args: Array[String]) { var s1  = Student(001, "Amit verma", 20, "Mumbai") var s2  = Student(002, "sumit sharma", 15, "Delhi") var s3  = Student(003, "vihit verma", 18, "Pune") var s4  = Student(004, "nimit shah", 20, "Bihar") var s5  = Student(001, "Amit verma", 20, "Mumbai") var result = s1 == s5 println("Result if they are equal or not ::") println(result) } }

Output:

Conclusion

Scala case classes are other normal classes in scala. We also have a case object with us. These classes are immutable and do not compare the object’s reference when it comes to checking object is equal or not.

Recommended Articles

This is a guide to Scala Case. Here we discuss How does Case Classwork in Scala and Examples, along with the codes and outputs. You may also have a look at the following articles to learn more –

You're reading How Does Case Classwork In Scala With Examples?

How Does Classtag Work In Scala?

Definition of Scala Classtag

Web development, programming languages, Software testing & others

Syntax:

As now we know is it the approach to determine and handle the element at the runtime so we have different approaches for that. Let’s have a look at its syntax as per the Scala doc see below;

def method_name[T]: return_type { }

In the above lines of syntax, we have to give the name of the method followed by the return type. This method will return any type of element.

How does ClassTag Work in Scala?

As now we know that classtag is used to handle the element whose types are unknown at the runtime. If we do not handle this properly then we can get many exceptions while programming, for example, classCastException, etc. We have ‘Any’ type in Scala, that can hold any element type inside it. for example, it can be Integer, String. float, and many more. So let’s see one scenario where we have a map that can take up ‘Any’ as the value, but we have to handle it properly otherwise, the code will not work because, at the compile time, we do not know what kind of element it is holding, at runtime only we will get to know.

Let’s have a scenario where we need to handle our array data properly in order to avoid any exceptions while handling the data; see below;

Map[String, Any]: This map is holding key-value pair as String and Any. We can easily handle the key ‘String’ here because the element type is known at compile time only. But if we look at the ‘Any’ value of the map, then we cannot guess what it will hold. It can be anything, so we will see some approaches where we will see how to handle this situation using ClassTag[T] in Scala. See below;

We have three different approaches to this. We will discuss each of them in detail with all the scenarios and exceptions we can get while doing this let’s discuss each of them in detail see below;

To check the instance of the element.

To assign them to any specific type

Use of classtag in scala

1. To Check the Instance of The Element var result = map("12").asInstanceOf[Int];

In the above lines of code, we have our map in which the value comes out to be ’12’, which can be easily cast to int without any error or exception. This will run fine until the value is coming out to be an integer here. But the problem will occur when the value is string here. Let’s take one code snippet see below;

var result = map("Hello").asInstanceOf[Int];

In the above lines of code, we are trying to cast a string then we will get classCastException here. So we are not able to handle this properly, and this line of code is erroneous. We can resolve this by using the classtag in Scala. This can only be determined at runtime only.

2. To Assign Them to Any Specific Type

In this approach, what we are trying to do is we are directly assigning the value to a variable without typecast, but we will going to get the error at compile time only. Let’s see one code snippet where we can understand it better. See below;

var result: Int = map("Hello");

In the above line of code, we are assigning values to solve this problem. We can use an instance of the method here available in Scala, but this is also not the correct approach to solve this because we have already seen we might get some different values while typecasting it, so better to take a better approach to solve this. Here we can use ClassTag[T] available in Scala.

3. Use of ClassTag in Scala def getThevaleFromMap[T]():Option[t]{ } Examples of Scala ClassTag

In this example, we are converting the map values by using ClassTag[T] approach, this is a simple program for beginners to understand it better.

Example

Code:

object Main extends App{ def getConvertedvalues[T](myKey: String, mymap: Map[String, Any]): Option[T] = { println("Here we are calculationg values : ") mymap.get(myKey) match { } } var result1: Option[String] = getConvertedvalues[String]("String1", mymap1) println("Result is after following classtag is  :::") println(result1) println("**********************************************************************") var result2: Option[String] = getConvertedvalues[String]("String2", mymap1) println("Result is after following classtag is  :::") println(result1) println("**********************************************************************") var result3: Option[Int] = getConvertedvalues[Int]("String3", mymap1) println("Result is after following classtag is  :::") println(result1) println("**********************************************************************") var result4: Option[Int] = getConvertedvalues[Int]("String4", mymap1) println("Result is after following classtag is  :::") println(result1) println("**********************************************************************") var result5: Option[Int] = getConvertedvalues[Int]("String5", mymap1) println("Result is after following classtag is  :::") println(result1) println("**********************************************************************") }

Output:

Conclusion

By using classtag we can handle the element of list and map or collection we can say at runtime when we are not aware of the element type at the compile time; this approach or the use of classtag can prevent to occur various errors or exceptions in the program like Incompatible type, classCastException and many more makes our program more scalable and reduce the number of lines of code that being return for other return types.

Recommended Articles

We hope that this EDUCBA information on “Scala Classtag” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Save Function Works In Docker With Examples?

Introduction to Docker Save

The ‘docker save’ is used to save one or more than one image to a tar archive. It includes all parent layers, and all tags or versions. It is by default streamed to STDOUT, however, we can write to a file, instead of STDOUT by specifying a flag. This command is very useful when we have to use Docker images on different machines without using a registry or repository. We can also compress or save the image to a chúng tôi file using gzip.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

$docker save [OPTIONS] IMAGE [IMAGE…]

–output, -o: It is used to redirect the output to a file

–help, -h: It is used to get help about the command.

How save function works in Docker?

As we know, it is used to save Docker images to an archive. When we run this command from the command line, the Docker daemon saves the mentioned Docker image as an archive. We can then share that archive with different teams or to different computers and so on. Now, we need to load that archive file, in order to use that image. When we load that archive file again, it creates a Docker image.

Examples

Let’s understand the whole process with an example.

Scenario: We are going to save a Docker image and then will load it after deleting the existing image.

Step 1. Let’s check available Docker images locally using the below command:

docker image ls

Explanation: – In the above snapshot, we can see that there are two images available, let’s take the ‘ubuntu’ Docker image with the ‘latest’ tag. If the image is not available locally, pull it from the public registry that is chúng tôi using the below command:

docker pull ubuntu

Note: We can use any Docker images; it should be available locally.

Step 2. Now, we have a Docker image available locally let’s save it to an archive file as shown below:

ls my-ubuntu2.tar

Explanation: In the above snapshot, we can see that the ‘-o’ option has been used to save it to an archive and the name of the archive is ‘my-ubuntu.tar’. We can also use redirection instead of the ‘-o’ option to redirect the output to an archive file as shown below:

ls my-ubuntu2.tar

Step 3. Let’s verify by deleting exiting image and loading it from archive using below command:

docker image ls

Explanation: In the above snapshot, we have deleted the ‘ubuntu’ image that we have verified using the second command and then we have loaded the image using the archive file in which we have saved the image earlier. We have to use the ‘-i’ option to instruct the Docker daemon to load the image from an archive file instead of STDOUT. Finally, we have checked the locally available images to verify and we can see that the image is available again.

Scenario: Save multiple images at once.

Step 1. Let’s save two Docker images Ubuntu and nginx to an archive file as shown below:

docker save -o chúng tôi ubuntu nginx:alpine

Step 2. Let’s verify it as well using the same way we did earlier:

docker image ls

Explanation: As per the above example, we can understand that we can save multiple images in a single archive, so we load it again, it will load all the images that were saved using the ‘docker save’ command.

Scenario: Save Docker images to a chúng tôi file.

Solution: We can do it by using the gzip command. It compresses the tar and makes it smaller in size. We can run the below command to save the images to a chúng tôi file:

ll chúng tôi my-images2.tar.gz

Explanation: In the above snapshot, we can see that the ‘my-images2.tar.gz’ file is much smaller than the ‘my-images.tar’ file.

Advantages

We can archive the Docker images if not in use, for example, old builds are not required after a new build is released, however, we have to keep it for some time before removing it so better we can archive those images.

We can save a lot of disk space if we also compressing the archive using gzip.

Conclusion

The ‘docker save’ is a handy command to save the images only, it does not save changes made to the image by any running container using that image. We have one more command to save the images and that is ‘docker image save’. This command works similarly to the ‘docker save’ command.

Recommended Articles

This is a guide to Docker Save. Here we also discuss the introduction and How save function work in docker? along with different examples and its code implementation. You may also have a look at the following articles to learn more –

How To Use Keras Model With Examples?

Introduction to Keras Model

Keras models are special neural network-oriented models that organize different layers and filter out essential information. The Keras model has two variants: Keras Sequential Model and Keras Functional API, which makes both the variants customizable and flexible according to scenario and changes. Moreover, it makes the functional APIs give a set of inputs and outputs with a single file, giving the graph model’s look and feel accordingly. It is a library with high-level language considered for deep learning on top of TensorFlow and Theano. It is written in Python language.

Start Your Free Data Science Course

What is Keras Model?

Keras model is used for designing and working with neural network types that are used for building many other similar formats of architecture possessing training and feeding complex models with structures. It comprises many graphs that support the representation of a model in some other ways, with many other configurable systems and patterns for feeding values as part of training. Moreover, it provides modularity, which helps make flexible and well-suited models for customization and support. Two approaches based on this help develop sequential and functional models.

How to Use Keras model?

As the Keras model is a python-based library, it must be used for flexibility and customized model design, especially for prediction.

Keras model has its way of detecting trends with behavior for modeling and prediction.

Keras model uses a model.predict() class and reconstructed_model.predict(), which have their own significance.

Predict () class within a model can be used for creating and fitting trained data using prediction.

Another class, i.e., reconstructed_model.predict() within a model, is used to save and load the model for reconstruction. A reconstructed model compiles and retains the state into optimization using either historical or new data.

Certain components will also get incorporated or are already part of the Keras model for customization, which is as follows:

Optimizer: It is used for compiling a Keras model by passing certain arguments containing the Optimizer loss function to minimize and handle any unpredictable loss.

Loss of set and metrics: A model is compiled and is used in a way where it is used for including losses and metrics that will get taught at the time of training or modeling.

Weights: Certain input parameters must be fed to the model for required output within a Keras model.

Create Keras Model

Ways to create a model using Sequential API and Functional API

1. Using Sequential API

The idea is to create a sequential flow within layers that possess some order and help make certain flows from top to bottom, giving individual output. It helps in creating an ANN model just by calling a Sequential API() using the Keras model package, which is represented below:

model_any = sequential()

The next step is to add a layer for which a layer needs to be created, followed by passing that layer using add() function within it

model_any.add( inpt_layer)

Next, Is to access the model: which means to provide the relevant information about the layers defined or added as part of the model.

layers=model.layers

Model. input: will provide all relevant input then similarly model. the output will give relevant information about the same.

Serializing the model is another important step for serializing the model into an object like JSON and then loading it like

Then, the Summarization of the model happens, followed by Training and prediction of the model, which include components like compile, evaluate, fit, and predict.

2. Using Functional API

Functional API is an alternative to Sequential API, where the approach is almost identical. Still, it does support and gives flexibility in terms of a certain complex model where an instance is created first, followed by connecting the layers with an input or output.

Let’s create a model by importing an input layer.

Creating an input layer where we can define dimensional input shape for a model is as follows:

data=Input(shape=(5,6)

Add a dense layer for the input

print(layer)

Define your model accordingly:

Create a model with both input and output layers using functional API:

model=Model(inpt=data, otput=layer)

Keras Model Types

Keras model represents and gels well with Deep learning; it gives the following ways to generate model types:

1. Sequential Type Model

As its name suggests, the sequential type model mostly supports and creates sequential type API, which tries to arrange the layers in a specific sequence and order.

Most deep learning and neural network have layers provisioned in a sequence for transferring data and flow from one layer to another sequence data.

2. Functional API model

This model is used to create and support some complex and flexible models.

This also helps make Directed acyclic graphs (DAGs) where the architecture comprises many layers that need to be filtered from top to bottom.

It also helps define and design branches within the architecture with some inception blocks, functions, etc.

Highlight a few famous examples supporting the Functional API model Squeeze Net, Xception, ResNet, GoogleNet, and Inception.

3. Model Subclassing

Model subclassing is a way to create a custom model comprising most of the functions and classes that are the root and internal models to the full custom forward pass model.

It does help in assisting and supporting Functional or sequential types of models for manipulation and testing.

Examples of Keras Model

Below are the different examples of the Keras Model:

Example #1

x_val_0 = x_train_0[-10020:] y_val_0 = y_train_0[-10010:] x_train_0 = x_train_0[:-10000] y_train_0 = y_train_0[:-10060] print(“prediction shape:”, prediction.shape)

Example #2

This program represents the creation of a model using Sequential API ().

mode.add(Dense(16))

Example #3

This program represents the creation of a model with multiple layers using functional API()

model=Model(inputsval=[input_1,input_2],outputsval=[layer_1,layer_2,layer_3])

Conclusion

Keras model is used for a lot of model analysis related to deep learning and gels well with all types of the neural network, which requires an hour as most of the task carried out contains an association with AI and ANN. Tensorflow, when incorporated with Keras, makes wonder and performs quite well in analysis phases of different types of models.

Recommended Articles

This is a guide to Keras Model. Here we discuss the definition, how to use and create Keras Model, and examples and code implementation. You may also have a look at the following articles to learn more –

How Does Internal Controls Work With Objectives?

Introduction to Internal Controls

Start Your Free Investment Banking Course

Download Corporate Valuation, Investment Banking, Accounting, CFA Calculator & others

Internal controls are the various procedures and steps implemented by different business firms to ensure the highest integrity of their financial and accounting information and to promote accountability. Internal controls also come in handy to detect the concern areas of fraud and stop them from happening. Apart from the above-discussed functions, internal controls also come to use in operational efficiency, which enhances the accuracy and timeliness of financial reporting.

Objectives of Internal Controls

The objectives of internal controls are as follows:

To make sure every transaction gets systematically recorded on a sequential basis.

Grant enough security to the company’s assets to prevent them from being used unauthorizedly.

To compare assets recorded in the books with the existing ones and to this in a fixed interval to find any discrepancy.

To systematically evaluate the complete accounting process used in the authorization of transactions?

Conduct proper checks and controls to review if the entire organization is in good shape and to find any loopholes.

To make sure optimum utilization of resources is taking place within the firm.

Ensure the financial statements are prepared following the accounting concepts and principles guidelines.

Principles of Internal Controls

The first and foremost principle of accounting control is establishing responsibilities.

Maintaining records in sequential order is very important.

The segregation of duties is also an essential principle of accounting control.

Rotation of employees on a mandatory basis is needed.

The usage of technology control is a must.

Regular independent audits or reviews must be conducted.

Insuring assets must be done by bonding with key employees.

How does it Work?

Internal controls are guided by the Sarbanes-Oxley Act of 2002 when there were a lot number of fraud cases reported in early 2000 at many US companies. Corporate governance came under a lot of pressure, where managers were responsible for the financial reporting, and an audit trail was created. Managers who were found guilty of any discrepancy were penalized and faced criminal penalties.

Components of Internal Control

It is essential to the other four components and sets up the structure at the top of a business firm and decides on the discipline and design of the organization.

Risk Assessment: Identification and analysis of risk which could stop a firm from achieving its goals.

Control Activities: These are the steps and procedures to ensure the organization that all the directives given by the management are being followed.

Information and Communication: This is related to the timely transfer of information that helps other employees perform their responsibilities.

Monitoring: This is conducted by top management, enabling them to see that all controls are well in place and performed without any gap.

Examples 0f Internal Control

Bank Reconciliations: One very basic example of internal control can be bank reconciliations, where the records of all payments and receipts which are recorded in a business ledger are reconciled to the bank statement to see if there is any discrepancy.

Audit: Audit is one of the most prominent examples of internal control. An external party is hired to give their opinion on the accuracy and integrity of the company’s books of account.

Procurement Policies: One area where internal control can be applied is the company’s procurement policies. The firms can establish a set mechanism and vendor list to procure the required items and demonstrate a thorough check on them.

Responsibilities of Internal Controls

The responsibilities of internal controls are as follows:

The CEO is the prime connect for applying internal control and makes sure he passes practical directives to his managers to conduct the business.

Internal controls ensure there is no scope for fraud in the system and prevent it from happening.

Internal control ensures that the financial and accounting information has the highest integrity and reliability.

Internal controls assure that all the necessary accounting principles have been followed.

It also protects the interest of the stakeholders who have invested in the company.

Scope of Internal Controls

The scope of internal control is for the firm’s overall governance and may reach broader areas like risk management and technology control.

It ensures that accounting transactions are reliable and recorded by following the accounting principles.

It is related to the distribution of authority and has a scope in the organization’s decision-making process.

Limitations

The Control system may turn out to become redundant with time.

It may not prevent the collusion of two or more people.

It still cannot fully safeguard a firm from human error.

Most of the controls will tend to go towards transactions of the usual nature.

It also bears a cost to implement the same in the business.

Conclusion

Internal control forms the crux of any business if appropriately applied. Indeed the benefits of it are a lot more than the limitations it faces. Internal controls instill the concept of assurance and reliability in the firm, and stakeholders also find such firms reliable enough to park their savings.

Recommended Articles

This is a guide to Internal Controls. Here we also discuss internal controls’ objectives and principles, with scope and responsibilities. You may also have a look at the following articles to learn more –

Working Of Import Directory In Sass With Examples

Introduction to SASS Import

SASS stands for Syntactically Awesome Style Sheet which is a css pre-processor that provides a feature to your stylesheet mark-up to make the writing styles in different ways.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The @import is a directive in SASS pre-processor which is used to keep associated code in separate files. It allows us to continue code in one file as opposed to keeping the same code over numerous files. The @import directive can be used to import SCSS files in our main file, therefore essentially, we can combine multiple files together.

The .css will be the extension for a file

The url() can be a filename

The media queries can be used using @import directive

Syntax

The syntax for @import directive in SASS can be written as shown below:

Syntax:

@import mystyle.sass;

The above line includes the style sheet into another style sheet by using the @import directive. For instance, let’s take a file as chúng tôi with the below code:

Code:

a { color: blue; } body { font-size: 15px; background-color: red; }

Now, create another file with the name chúng tôi along with the below code:

Code:

@import "demo.scss"; p { color: green; font-weight: 200; }

When you compile the code, you will get the below code with the combination of above both files:

Code: demo2.css

a { color: blue; } body { font-size: 15px; background-color: red; } p { color: green; font-weight: 200; } Working of Import Directory in SASS

The import directive enables us to add several styles and can be broken into separate files to import them into one another. In this way, the SASS import directive works speedily to edit the style sheet.

Different plain CSS imports need the browser to make multiple HTTP requests as it displays your web page, and during the compilation time, Sass imports are handled entirely.

SASS works on the @import CSS. It does not involve an HTTP request. Instead, it usually takes the file we want to import and integrates it with the file you are importing into, so you can represent the web browser with a single CSS file.

Examples to Implement SASS Import Directory

Below are the examples:

Example #1

To run SASS files, you need to install Ruby for executing SASS programs.  Create a file with name sass_import.html with the below code:

Code: sass_import.html

Educba is online teaching providing server which helps various stream people or candidates to upgrade their knowledge respective to their domain.

Now create an scss file with name import_demo.scss and put the below code.

Code: import_demo.scss

html, body { margin: 0; padding: 0; } .styledemo { font-size:25px; background-color: green; }

Put the above both two files in the root folder of the installed ruby folder. Now open the command prompt and run the below command to watch the file and communicates it to SASS and updates the CSS file every time SASS file changes.

Code:

sass --watch import_demo.scss: import_demo.css

The above command will create a CSS file and called import_demo.css in the same folder where Ruby is installed. The import_demo.css file includes the below code.

Code:

html, body { margin: 0; padding: 0; } .styledemo { font-size: 25px; background-color: green; }

Output: Now, execute the html file and open in the browser and you will get the below result:

Example #2

In this example, we have used @import directive which imports the content of one file into another file. Let’s create a html file and save the below code as import_demo_example.html.

Code:

Now create a file called sass_import.scss with the below code:

Code:

ul{ margin: 0; padding: 1; } li{ color: #82BBDB; }

Code:

@import "sass_import"; .block { background: #26688D; } h2 { color: #B98D25; }

Explanation: In the above file, we are importing a sass-import file which adds its content into in this file when you made changes to the scss file. The @import could include the style sheet inside the other style sheets. The comprised files could either be placed on a similar server or added with a URL to a directory on the alternative server.

Now open the command prompt and run the below command to watch the file and communicates it to SASS and updates the CSS file every time SASS file changes.

Code:

sass –watch sass_import_demo.scss: sass_import_demo.css

Now, execute the file with the above command and it will create the sass_import_demo.css file with the below code:

Code: sass_import_demo.css

ul { margin: 0; padding: 1; } li { color: #82BBDB; } .block { background: #26688D; } h2 { color: #B98D25; }

Output: Now, execute the html file and open in the browser and you will get the below result.

Benefit of SASS Import

The main benefit of using the @import directive is, we can merge several files using @import and then compile the main file. Therefore, as a result, we will have only one CSS file and hence, the browser will not have to create more than one HTTP request to load up separate CSS files.

Conclusion

The @import Sass directive is one of the CSS rules which can help to maintain the code and break down the larger files into tiny files and also, facilitates import other files and ultimately one top-level file that will be compiled into CSS. If you are utilizing Sass pre-processor, you will create a good structure for your stylesheets. The structure without @import directive in Sass pre-processor is not possible to do properly.

Recommended Articles

This is a guide to SASS Import. Here we discuss syntax to SASS Import, working off and examples to implement with knowing its benefits. You can also go through our other related articles to learn more –

Update the detailed information about How Does Case Classwork In Scala With Examples? on the Minhminhbmm.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!