尊敬的 微信汇率:1円 ≈ 0.046078 元 支付宝汇率:1円 ≈ 0.046168元 [退出登录]
SlideShare a Scribd company logo
   Introducing Annotations 


                                      Rishi Khandelwal
                                      Software Consultant     
                                          Knoldus
AGENDA
●
    What is Annotations.


    Why have Annotations.


    Syntax of Annotations.


    Types Of Annotation


    Standard Annotations.


    Example of Annotation


    Writing your own annotations


    Comparison of scala annotation with java.
What is Annotations
➔
    Annotations are structured information added to program source
    code.

➔
    Annotations associate meta-information with definitions.

➔
    They can be attached to any variable, method, expression, or
    other program element

➔
    Like comments, they can be sprinkled throughout a program .

➔
     Unlike comments, they have structure, thus making them easier
    to machine process.
Why have Annotations

Meta Programming Tools : They are programs that take other programs as
                         input.
Task performed :

1. Automatic generation of documentation as with Scaladoc.

2. Pretty printing code so that it matches your preferred style.

3. Checking code for common errors such as opening a file but, on some
   control paths, never closing it.

4. Experimental type checking, for example to manage side effects or
   ensure ownership properties.
Improvement after using Annotations :

1. Automatic generation of documentation as with Scaladoc.

➔
    A documentation generator could be instructed to document certain
    methods as deprecated.


2. Pretty printing code so that it matches your preferred style.

➔
    A pretty printer could be instructed to skip over parts of the program
    that have been carefully hand formatted.
Improvement after using Annotations :

3. Checking code for common errors such as opening a file but, on some
   control paths, never closing it.

➔
    A checker for non-closed files could be instructed to ignore a particular
    file that has been manually verified to be closed.


4. Experimental type checking, for example to manage side effects or
   ensure ownership properties.

➔
    A side-effects checker could be instructed to verify that a specified
    method has no side effects.
Syntax of annotations
Annotations are allowed on any kind of declaration or definition, including
vals, vars, defs, classes, objects, traits, and types.

●
    Method Annotation:        @deprecated def bigMistake() = //..

●
    Classes Annotation:       @serializable class C { ... }

●
    Expressions Annotation:   (e: @unchecked) match {
                                 // non-exhaustive cases...
                              }
●
    Type Annotation :         String @local

●
    Variable Annotation :     @transient @volatile var m: Int
Syntax of annotations

Annotations have a richer general form:
@annot(exp1 , exp2 , ...) {val name1 =const1 , ..., val namen =constn }

●
    The annot specifies the class of annotation.

●
    The exp parts are arguments to the annotation

●
    The name=const pairs are available for more complicated annotations.

●
    These arguments are optional, and they can be specified in any order.

●
    To keep things simple, the part to the right-hand side of the equals sign
     must be a constant.
Types of Annotations
●
    No arguments Annotations :

    For no arguments annotations like @deprecated ,leave off the parentheses,
     but we can write @deprecated() .

●
    Argument annotations

    For annotations that do have arguments, place the arguments in
    parentheses. example, @serial(1234) .
Types of Annotations
●
    The precise form of the arguments depends on the particular annotation
    class.

●
    Most annotation processors allow only constants such as 123 or "hello".

●
    The compiler itself supports arbitrary expressions, however, so long as they
     type check.

    for example, @cool val normal = "Hello"
                 @coolerThan(normal) val fonzy = "Heeyyy"
Standard annotations
Deprecation : (@deprecated)

●
    This is used with class and methods.

●
    When anyone calls that method or class will get a deprecation warning.

●
    Syntax : @deprecated def bigMistake() = //..


Volatile Fields : (@volatile)

●
 This annotations helps programmers to use mutable state in their
concurrent programs.
Standard annotations
●
    It informs the compiler that the variable in question will be used by multiple
    threads

●
    The @volatile keyword gives different guarantees on different platforms.

●
    On the Java platform, it behaves same as Java volatile modifier.


●
    Binary serialization :

●
    It means to convert objects into a stream of bytes and vice versa.

●
    Many languages include a framework for binary serialization.
Standard annotations
●
    Scala does not have its own serialization framework.

●
    Scala provides 3 annotations that are useful for a variety of frameworks.

1. (a) The first annotation indicates whether a class is serializable at all

     (b) Add a @serializable annotation to any class which we would like to
         be serializable.

2. (a) The second annotation helps deal with serializable classes changing as
       time goes by.

    (b) We can attach a serial number to the current version of a class by
        adding an annotation like @SerialVersionUID(<longlit>)
Standard annotations
    (c) If we want to make a serialization-incompatible change to our class,
        then we can change the version number.

3. (a) Scala provides a @transient annotation for fields that should not be
      serialized at all.

    (b) The framework should not save the field even when the surrounding
         object is serialized.


Automatic get and set methods : (@scala.reflect.BeanProperty)

●
    Scala code normally does not need explicit get and set methods for fields.
Standard annotations
●
    Some platform-specific frameworks do expect get and set methods.

●
    For that purpose, Scala provides the @scala.reflect.BeanProperty
    annotation.

●
    The generated get and set methods are only available after a compilation
    pass completes.

●
    We cannot call these get and set methods from code we compile at the same
    time as the annotated fields.

●
    This should not be a problem in Scala, because in Scala code we can access
    the fields directly.
Standard annotations
●
    This feature is intended to support frameworks that expect regular
    get and set methods, and typically we do not compile the framework and
    the code that uses it at the same time.


Unchecked : (@unchecked)

The @unchecked annotation is interpreted by the compiler during pattern
●


matches.

●
 It tells the compiler not to worry if the match expression seems to
leave out some cases.
Example of annotations
Scala Class : (Reader.scala)
package ppt
import java.io._
class Reader(fname: String) {
  private val in = new BufferedReader(new FileReader(fname))
  @throws(classOf[IOException])
  def read() = in.read()
 }
Java Class :(AnnotaTest.java)
package test;
import ppt.Reader; // Scala class !!
public class AnnotaTest {
   public static void main(String[] args) {
      try {
         Reader in = new Reader(args[0]);
         int c;
         while ((c = in.read()) != -1) {
            System.out.print((char) c);
         } } catch (java.io.IOException e) {
         System.out.println(e.getMessage());
      } }}
Example of annotations
Scala Class : (Reader.scala)
package ppt
import java.io._
class Reader(fname: String) {
  private val in = new BufferedReader(new FileReader(fname))
  @throws(classOf[IOException])
  def read() = in.read()
 }
Java Class :(AnnotaTest.java)
package test;
import ppt.Reader; // Scala class !!
public class AnnotaTest {
   public static void main(String[] args) {
      try {
         Reader in = new Reader(args[0]);
         int c;
         while ((c = in.read()) != -1) {
            System.out.print((char) c);
         } } catch (java.io.IOException e) {
         System.out.println(e.getMessage());
      } }}
Example of annotations
Scala Class : (Person.scala)
Package my.scala.stuff;
import scala.reflect.BeanProperty
class Person {
 @BeanProperty
 var name = "Dave"

    var age = 36
}
Java Class :(UsingBeanProperty.java)
package my.java.stuff;
import my.scala.stuff.*;
public class UsingBeanProperty {
  public UsingBeanProperty(Person p) {
     // Scala has added this method for us
     System.out.println(p.getName());

         // Since we didn't annotate "age", we can't do this:
         System.out.println(p.getAge()); // compile error!
     }
}
Writing your own annotations
To make an annotation that is visible to Java reflection, we must use Java notation and
compile it with javac.
Example :
Java class ; (Ignore.java)
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Ignore { }

Scala Object : (Tests.scala)
object Tests {
@Ignore
def testData = List(0, 1, -1, 5, -5)
def test1 {
assert(testData == (testData.head :: testData.tail))
}
def test2 {
assert(testData.contains(testData.head))
}}
Writing your own annotations
To see when these annotations are present,use the Java reflection APIs.
Example :
Tests.getClass.getMethods foreach {
 method =>
 if (method.getAnnotation(classOf[Ignore]) == null &&
method.getName.startsWith("test"))
   {
      println(method)
   }}


Output :
public void ppt.Tests$.test2()
public void ppt.Tests$.test1()
Comparison of scala annotation with java

        Scala                        Java
 scala.SerialVersionUID       serialVersionUID (field)
 scala.cloneable              java.lang.Cloneable
 scala.deprecated             java.lang.Deprecated
 scala.inline                 no equivalent
 scala.native                 native (keyword)
 scala.remote                 java.rmi.Remote
 scala.serializable           java.io.Serializable
 scala.throws                 throws (keyword)
 scala.transient              transient (keyword)
 scala.unchecked              no equivalent
 scala.volatile               volatile (keyword)
 scala.reflect.BeanProperty   Design pattern
Annotations

More Related Content

What's hot

Academic writing
Academic writingAcademic writing
Academic writing
Gita RahMa
 
Academic writing
Academic writingAcademic writing
Academic writing
Mhel Marquez
 
Summarizing and Paraphrasing
Summarizing and ParaphrasingSummarizing and Paraphrasing
Summarizing and Paraphrasing
lcslidepresentations
 
Summarizing, paraphrasing, synthesizing
Summarizing, paraphrasing, synthesizingSummarizing, paraphrasing, synthesizing
Summarizing, paraphrasing, synthesizing
theLecturette
 
How To Write An Introduction
How To Write An IntroductionHow To Write An Introduction
How To Write An Introduction
muguu_908
 
Pre-Writing Strategies
Pre-Writing StrategiesPre-Writing Strategies
Pre-Writing Strategies
MGC1987
 
Newspaper Article
Newspaper Article Newspaper Article
Newspaper Article
Jools Jerome
 
MLA vs APA
MLA vs APAMLA vs APA
MLA vs APA
Draizelle Sexon
 
MLA Style
MLA StyleMLA Style
English for app
English for appEnglish for app
English for app
REMRYAN REBUTAZO
 
Data types
Data typesData types
Data types
Nokesh Prabhakar
 
Citations- APA and MLA
Citations- APA and MLACitations- APA and MLA
Citations- APA and MLA
hcook_caldwell
 
Critical reading
Critical readingCritical reading
Critical reading
Stephanie Mae Manuel
 
Critical reading
Critical readingCritical reading
Critical reading
Lauren Birdsong
 
Resume writing
Resume writingResume writing
Resume writing
AMNA IJAZ
 
13 Creative Writing Exercises
13 Creative Writing Exercises13 Creative Writing Exercises
13 Creative Writing Exercises
ESSAYSHARK.com
 
Review writing
Review writing Review writing
Review writing
Zahida Pervaiz
 
What is Academic Writing? Types of Academic Writing
What is Academic Writing? Types of Academic WritingWhat is Academic Writing? Types of Academic Writing
What is Academic Writing? Types of Academic Writing
HirearticleWriter
 
Summarizing powerpoint
Summarizing powerpointSummarizing powerpoint
Summarizing powerpoint
stefaniejanko
 
How To...Write A Conclusion
How To...Write A ConclusionHow To...Write A Conclusion
How To...Write A Conclusion
Medway High School
 

What's hot (20)

Academic writing
Academic writingAcademic writing
Academic writing
 
Academic writing
Academic writingAcademic writing
Academic writing
 
Summarizing and Paraphrasing
Summarizing and ParaphrasingSummarizing and Paraphrasing
Summarizing and Paraphrasing
 
Summarizing, paraphrasing, synthesizing
Summarizing, paraphrasing, synthesizingSummarizing, paraphrasing, synthesizing
Summarizing, paraphrasing, synthesizing
 
How To Write An Introduction
How To Write An IntroductionHow To Write An Introduction
How To Write An Introduction
 
Pre-Writing Strategies
Pre-Writing StrategiesPre-Writing Strategies
Pre-Writing Strategies
 
Newspaper Article
Newspaper Article Newspaper Article
Newspaper Article
 
MLA vs APA
MLA vs APAMLA vs APA
MLA vs APA
 
MLA Style
MLA StyleMLA Style
MLA Style
 
English for app
English for appEnglish for app
English for app
 
Data types
Data typesData types
Data types
 
Citations- APA and MLA
Citations- APA and MLACitations- APA and MLA
Citations- APA and MLA
 
Critical reading
Critical readingCritical reading
Critical reading
 
Critical reading
Critical readingCritical reading
Critical reading
 
Resume writing
Resume writingResume writing
Resume writing
 
13 Creative Writing Exercises
13 Creative Writing Exercises13 Creative Writing Exercises
13 Creative Writing Exercises
 
Review writing
Review writing Review writing
Review writing
 
What is Academic Writing? Types of Academic Writing
What is Academic Writing? Types of Academic WritingWhat is Academic Writing? Types of Academic Writing
What is Academic Writing? Types of Academic Writing
 
Summarizing powerpoint
Summarizing powerpointSummarizing powerpoint
Summarizing powerpoint
 
How To...Write A Conclusion
How To...Write A ConclusionHow To...Write A Conclusion
How To...Write A Conclusion
 

Viewers also liked

Java Annotation
Java AnnotationJava Annotation
Java Annotation
karthik.tech123
 
How to annotate
How to annotateHow to annotate
How to annotate
Michelle Alspaugh
 
Annotations and cornell note taking
Annotations and cornell note takingAnnotations and cornell note taking
Annotations and cornell note taking
carawc
 
Annotating Text: A Powerful Reading Tool
Annotating Text: A Powerful Reading ToolAnnotating Text: A Powerful Reading Tool
Annotating Text: A Powerful Reading Tool
Pamela Santerre
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
Ecommerce Solution Provider SysIQ
 
Reading and Annotation
Reading and AnnotationReading and Annotation
Reading and Annotation
themiddaymiss
 
Annotating a text
Annotating a textAnnotating a text
Annotating a text
March91989
 
How to annotate non fiction text
How to annotate non fiction textHow to annotate non fiction text
How to annotate non fiction text
Shana Siegel
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
Meir Maor
 
Java annotations
Java annotationsJava annotations
Java annotations
FAROOK Samath
 
How to annotate
How to annotateHow to annotate
How to annotate
terlin95
 
Annotation Guide: Romeo and Juliet - William Shakespeare
Annotation Guide: Romeo and Juliet - William ShakespeareAnnotation Guide: Romeo and Juliet - William Shakespeare
Annotation Guide: Romeo and Juliet - William Shakespeare
Steven Kolber
 
CMS Documentation
CMS DocumentationCMS Documentation
CMS Documentation
kedavisn
 
Interactive web prototyping
Interactive web prototypingInteractive web prototyping
Interactive web prototyping
Ecommerce Solution Provider SysIQ
 
Java Generics: What it is and How to Implement it
Java Generics: What it is and How to Implement itJava Generics: What it is and How to Implement it
Java Generics: What it is and How to Implement it
Ecommerce Solution Provider SysIQ
 
Scala reflection
Scala reflectionScala reflection
Scala reflection
David Pichsenmeister
 
Chicago manual of style
Chicago manual of styleChicago manual of style
Chicago manual of style
Sadaqat Ali
 
Style Manuals
Style ManualsStyle Manuals
Style Manuals
unmgrc
 
Hair Transplant Results including male, female, eyelash, eyebrow, scalp and s...
Hair Transplant Results including male, female, eyelash, eyebrow, scalp and s...Hair Transplant Results including male, female, eyelash, eyebrow, scalp and s...
Hair Transplant Results including male, female, eyelash, eyebrow, scalp and s...
Bauman Medical Group, P.A.
 
Annotated Bibliography
Annotated BibliographyAnnotated Bibliography
Annotated Bibliography
BRYAN CARTER
 

Viewers also liked (20)

Java Annotation
Java AnnotationJava Annotation
Java Annotation
 
How to annotate
How to annotateHow to annotate
How to annotate
 
Annotations and cornell note taking
Annotations and cornell note takingAnnotations and cornell note taking
Annotations and cornell note taking
 
Annotating Text: A Powerful Reading Tool
Annotating Text: A Powerful Reading ToolAnnotating Text: A Powerful Reading Tool
Annotating Text: A Powerful Reading Tool
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
 
Reading and Annotation
Reading and AnnotationReading and Annotation
Reading and Annotation
 
Annotating a text
Annotating a textAnnotating a text
Annotating a text
 
How to annotate non fiction text
How to annotate non fiction textHow to annotate non fiction text
How to annotate non fiction text
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
 
Java annotations
Java annotationsJava annotations
Java annotations
 
How to annotate
How to annotateHow to annotate
How to annotate
 
Annotation Guide: Romeo and Juliet - William Shakespeare
Annotation Guide: Romeo and Juliet - William ShakespeareAnnotation Guide: Romeo and Juliet - William Shakespeare
Annotation Guide: Romeo and Juliet - William Shakespeare
 
CMS Documentation
CMS DocumentationCMS Documentation
CMS Documentation
 
Interactive web prototyping
Interactive web prototypingInteractive web prototyping
Interactive web prototyping
 
Java Generics: What it is and How to Implement it
Java Generics: What it is and How to Implement itJava Generics: What it is and How to Implement it
Java Generics: What it is and How to Implement it
 
Scala reflection
Scala reflectionScala reflection
Scala reflection
 
Chicago manual of style
Chicago manual of styleChicago manual of style
Chicago manual of style
 
Style Manuals
Style ManualsStyle Manuals
Style Manuals
 
Hair Transplant Results including male, female, eyelash, eyebrow, scalp and s...
Hair Transplant Results including male, female, eyelash, eyebrow, scalp and s...Hair Transplant Results including male, female, eyelash, eyebrow, scalp and s...
Hair Transplant Results including male, female, eyelash, eyebrow, scalp and s...
 
Annotated Bibliography
Annotated BibliographyAnnotated Bibliography
Annotated Bibliography
 

Similar to Annotations

Java Annotations
Java AnnotationsJava Annotations
Java Annotations
Serhii Kartashov
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
manaswinimysore
 
Java annotations
Java annotationsJava annotations
Java annotations
Sujit Kumar
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
Darshan Gohel
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
PrasannaKumar Sathyanarayanan
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
Professional Guru
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
Raghuveer Guthikonda
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Annotations
AnnotationsAnnotations
Annotations
swapna reniguntla
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
i i
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
Shivam Singhal
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
SudhanshiBakre1
 
Java notes
Java notesJava notes
Java notes
Upasana Talukdar
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
WebStackAcademy
 
Introduction
IntroductionIntroduction
Introduction
richsoden
 
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
mircodotta
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i
Nico Ludwig
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
SadhanaParameswaran
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 

Similar to Annotations (20)

Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
Annotations
AnnotationsAnnotations
Annotations
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
 
Java notes
Java notesJava notes
Java notes
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
 
Introduction
IntroductionIntroduction
Introduction
 
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)Managing Binary Compatibility in Scala (Scala Lift Off 2011)
Managing Binary Compatibility in Scala (Scala Lift Off 2011)
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 

More from Knoldus Inc.

Insights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability ExcellenceInsights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
Code Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis FrameworkCode Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
AWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS PresentationAWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
Amazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and AuthorizationAmazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web DevelopmentZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 
Facilitation Skills - When to Use and Why.pptx
Facilitation Skills - When to Use and Why.pptxFacilitation Skills - When to Use and Why.pptx
Facilitation Skills - When to Use and Why.pptx
Knoldus Inc.
 
Performance Testing at Scale Techniques for High-Volume Services
Performance Testing at Scale Techniques for High-Volume ServicesPerformance Testing at Scale Techniques for High-Volume Services
Performance Testing at Scale Techniques for High-Volume Services
Knoldus Inc.
 
Snowflake and its features (Presentation)
Snowflake and its features (Presentation)Snowflake and its features (Presentation)
Snowflake and its features (Presentation)
Knoldus Inc.
 
Terratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructureTerratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructure
Knoldus Inc.
 
Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)
Knoldus Inc.
 
Secure practices with dot net services.pptx
Secure practices with dot net services.pptxSecure practices with dot net services.pptx
Secure practices with dot net services.pptx
Knoldus Inc.
 
Distributed Cache with dot microservices
Distributed Cache with dot microservicesDistributed Cache with dot microservices
Distributed Cache with dot microservices
Knoldus Inc.
 
Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)
Knoldus Inc.
 
Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
Knoldus Inc.
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
Knoldus Inc.
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
Knoldus Inc.
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
Knoldus Inc.
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
Knoldus Inc.
 

More from Knoldus Inc. (20)

Insights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability ExcellenceInsights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability Excellence
 
Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)
 
Code Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis FrameworkCode Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis Framework
 
AWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS PresentationAWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS Presentation
 
Amazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and AuthorizationAmazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and Authorization
 
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web DevelopmentZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
 
Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.
 
Facilitation Skills - When to Use and Why.pptx
Facilitation Skills - When to Use and Why.pptxFacilitation Skills - When to Use and Why.pptx
Facilitation Skills - When to Use and Why.pptx
 
Performance Testing at Scale Techniques for High-Volume Services
Performance Testing at Scale Techniques for High-Volume ServicesPerformance Testing at Scale Techniques for High-Volume Services
Performance Testing at Scale Techniques for High-Volume Services
 
Snowflake and its features (Presentation)
Snowflake and its features (Presentation)Snowflake and its features (Presentation)
Snowflake and its features (Presentation)
 
Terratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructureTerratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructure
 
Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)
 
Secure practices with dot net services.pptx
Secure practices with dot net services.pptxSecure practices with dot net services.pptx
Secure practices with dot net services.pptx
 
Distributed Cache with dot microservices
Distributed Cache with dot microservicesDistributed Cache with dot microservices
Distributed Cache with dot microservices
 
Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)
 
Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
 

Annotations

  • 1.    Introducing Annotations   Rishi Khandelwal                                       Software Consultant    Knoldus
  • 2. AGENDA ● What is Annotations.  Why have Annotations.  Syntax of Annotations.  Types Of Annotation  Standard Annotations.  Example of Annotation  Writing your own annotations  Comparison of scala annotation with java.
  • 3. What is Annotations ➔ Annotations are structured information added to program source code. ➔ Annotations associate meta-information with definitions. ➔ They can be attached to any variable, method, expression, or other program element ➔ Like comments, they can be sprinkled throughout a program . ➔ Unlike comments, they have structure, thus making them easier to machine process.
  • 4. Why have Annotations Meta Programming Tools : They are programs that take other programs as input. Task performed : 1. Automatic generation of documentation as with Scaladoc. 2. Pretty printing code so that it matches your preferred style. 3. Checking code for common errors such as opening a file but, on some control paths, never closing it. 4. Experimental type checking, for example to manage side effects or ensure ownership properties.
  • 5. Improvement after using Annotations : 1. Automatic generation of documentation as with Scaladoc. ➔ A documentation generator could be instructed to document certain methods as deprecated. 2. Pretty printing code so that it matches your preferred style. ➔ A pretty printer could be instructed to skip over parts of the program that have been carefully hand formatted.
  • 6. Improvement after using Annotations : 3. Checking code for common errors such as opening a file but, on some control paths, never closing it. ➔ A checker for non-closed files could be instructed to ignore a particular file that has been manually verified to be closed. 4. Experimental type checking, for example to manage side effects or ensure ownership properties. ➔ A side-effects checker could be instructed to verify that a specified method has no side effects.
  • 7. Syntax of annotations Annotations are allowed on any kind of declaration or definition, including vals, vars, defs, classes, objects, traits, and types. ● Method Annotation: @deprecated def bigMistake() = //.. ● Classes Annotation: @serializable class C { ... } ● Expressions Annotation: (e: @unchecked) match { // non-exhaustive cases... } ● Type Annotation : String @local ● Variable Annotation : @transient @volatile var m: Int
  • 8. Syntax of annotations Annotations have a richer general form: @annot(exp1 , exp2 , ...) {val name1 =const1 , ..., val namen =constn } ● The annot specifies the class of annotation. ● The exp parts are arguments to the annotation ● The name=const pairs are available for more complicated annotations. ● These arguments are optional, and they can be specified in any order. ● To keep things simple, the part to the right-hand side of the equals sign must be a constant.
  • 9. Types of Annotations ● No arguments Annotations : For no arguments annotations like @deprecated ,leave off the parentheses, but we can write @deprecated() . ● Argument annotations For annotations that do have arguments, place the arguments in parentheses. example, @serial(1234) .
  • 10. Types of Annotations ● The precise form of the arguments depends on the particular annotation class. ● Most annotation processors allow only constants such as 123 or "hello". ● The compiler itself supports arbitrary expressions, however, so long as they type check. for example, @cool val normal = "Hello" @coolerThan(normal) val fonzy = "Heeyyy"
  • 11. Standard annotations Deprecation : (@deprecated) ● This is used with class and methods. ● When anyone calls that method or class will get a deprecation warning. ● Syntax : @deprecated def bigMistake() = //.. Volatile Fields : (@volatile) ● This annotations helps programmers to use mutable state in their concurrent programs.
  • 12. Standard annotations ● It informs the compiler that the variable in question will be used by multiple threads ● The @volatile keyword gives different guarantees on different platforms. ● On the Java platform, it behaves same as Java volatile modifier. ● Binary serialization : ● It means to convert objects into a stream of bytes and vice versa. ● Many languages include a framework for binary serialization.
  • 13. Standard annotations ● Scala does not have its own serialization framework. ● Scala provides 3 annotations that are useful for a variety of frameworks. 1. (a) The first annotation indicates whether a class is serializable at all (b) Add a @serializable annotation to any class which we would like to be serializable. 2. (a) The second annotation helps deal with serializable classes changing as time goes by. (b) We can attach a serial number to the current version of a class by adding an annotation like @SerialVersionUID(<longlit>)
  • 14. Standard annotations (c) If we want to make a serialization-incompatible change to our class, then we can change the version number. 3. (a) Scala provides a @transient annotation for fields that should not be serialized at all. (b) The framework should not save the field even when the surrounding object is serialized. Automatic get and set methods : (@scala.reflect.BeanProperty) ● Scala code normally does not need explicit get and set methods for fields.
  • 15. Standard annotations ● Some platform-specific frameworks do expect get and set methods. ● For that purpose, Scala provides the @scala.reflect.BeanProperty annotation. ● The generated get and set methods are only available after a compilation pass completes. ● We cannot call these get and set methods from code we compile at the same time as the annotated fields. ● This should not be a problem in Scala, because in Scala code we can access the fields directly.
  • 16. Standard annotations ● This feature is intended to support frameworks that expect regular get and set methods, and typically we do not compile the framework and the code that uses it at the same time. Unchecked : (@unchecked) The @unchecked annotation is interpreted by the compiler during pattern ● matches. ● It tells the compiler not to worry if the match expression seems to leave out some cases.
  • 17. Example of annotations Scala Class : (Reader.scala) package ppt import java.io._ class Reader(fname: String) { private val in = new BufferedReader(new FileReader(fname)) @throws(classOf[IOException]) def read() = in.read() } Java Class :(AnnotaTest.java) package test; import ppt.Reader; // Scala class !! public class AnnotaTest { public static void main(String[] args) { try { Reader in = new Reader(args[0]); int c; while ((c = in.read()) != -1) { System.out.print((char) c); } } catch (java.io.IOException e) { System.out.println(e.getMessage()); } }}
  • 18. Example of annotations Scala Class : (Reader.scala) package ppt import java.io._ class Reader(fname: String) { private val in = new BufferedReader(new FileReader(fname)) @throws(classOf[IOException]) def read() = in.read() } Java Class :(AnnotaTest.java) package test; import ppt.Reader; // Scala class !! public class AnnotaTest { public static void main(String[] args) { try { Reader in = new Reader(args[0]); int c; while ((c = in.read()) != -1) { System.out.print((char) c); } } catch (java.io.IOException e) { System.out.println(e.getMessage()); } }}
  • 19. Example of annotations Scala Class : (Person.scala) Package my.scala.stuff; import scala.reflect.BeanProperty class Person { @BeanProperty var name = "Dave" var age = 36 } Java Class :(UsingBeanProperty.java) package my.java.stuff; import my.scala.stuff.*; public class UsingBeanProperty { public UsingBeanProperty(Person p) { // Scala has added this method for us System.out.println(p.getName()); // Since we didn't annotate "age", we can't do this: System.out.println(p.getAge()); // compile error! } }
  • 20. Writing your own annotations To make an annotation that is visible to Java reflection, we must use Java notation and compile it with javac. Example : Java class ; (Ignore.java) import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Ignore { } Scala Object : (Tests.scala) object Tests { @Ignore def testData = List(0, 1, -1, 5, -5) def test1 { assert(testData == (testData.head :: testData.tail)) } def test2 { assert(testData.contains(testData.head)) }}
  • 21. Writing your own annotations To see when these annotations are present,use the Java reflection APIs. Example : Tests.getClass.getMethods foreach { method => if (method.getAnnotation(classOf[Ignore]) == null && method.getName.startsWith("test")) { println(method) }} Output : public void ppt.Tests$.test2() public void ppt.Tests$.test1()
  • 22. Comparison of scala annotation with java Scala Java scala.SerialVersionUID serialVersionUID (field) scala.cloneable java.lang.Cloneable scala.deprecated java.lang.Deprecated scala.inline no equivalent scala.native native (keyword) scala.remote java.rmi.Remote scala.serializable java.io.Serializable scala.throws throws (keyword) scala.transient transient (keyword) scala.unchecked no equivalent scala.volatile volatile (keyword) scala.reflect.BeanProperty Design pattern
  翻译: