Kotlin does not have checked exceptions, primitive types that are not classes, static members, or non-private fields like Java. Kotlin also does not have wildcard types. Instead, Kotlin uses declaration-site variance and type projections to allow flexible handling of generic types.
3 kotlin vs. java- what kotlin has that java does notSergey Bandysik
This document discusses Kotlin functions and lambda expressions. It explains that lambda expressions can be passed immediately as expressions or defined separately as functions. It also discusses that using higher-order functions can introduce runtime overhead which can be eliminated by inlining lambda expressions. Finally, it provides an example of an inline fun that demonstrates inlining and non-inlining of lambda expressions.
1 kotlin vs. java: some java issues addressed in kotlinSergey Bandysik
Kotlin addresses several issues in Java by controlling null references in the type system, eliminating raw types, making arrays invariant, defining proper function types, allowing use-site variance without wildcards, and removing checked exceptions. It fixes null references by allowing nullable types and non-null types, provides null-safe calls and operators like Elvis and safe casts, and filters nulls from collections.
The key difference between Java and Kotlin is given with details. Java is great and highly accepted across platforms, but its getting old.
Why is Kotlin taking so much preference and why should one prefer Kotlin? All the details are explained here.
Presented on 27th September 2017 to a joint meeting of 'Cork Functional Programmers' and the 'Cork Java Users Group'
Based on the Kotlin Language programming course from Instil. For more details see https://instil.co/courses/kotlin-development/
Category theory concepts such as objects, arrows, and composition directly map to concepts in Scala. Objects represent types, arrows represent functions between types, and composition represents function composition. Scala examples demonstrate how category theory diagrams commute, with projection functions mapping to tuple accessors. Thinking in terms of interfaces and duality enriches both category theory and programming language concepts. Learning category theory provides a uniform way to reason about programming language structures and properties of data types.
Some notes about programming in Scala: it covers Scala syntax and semantics, programming techniques, idioms, patterns. Many Scala features are introduced, from basic to intermediate and advanced. These are not introductory notes, but they assume a working knowledge with some other programming language (Java, C#, C++), object-oriented programming (OOP) concepts, and functional programming (FP) concepts.
Some key features of Scala include:
1. It allows blending of functional programming and object-oriented programming for more concise and powerful code.
2. The static type system allows for type safety while maintaining expressiveness through type inference, implicits, and other features.
3. Scala code interoperates seamlessly with existing Java code and libraries due to its compatibility with the JVM.
3 kotlin vs. java- what kotlin has that java does notSergey Bandysik
This document discusses Kotlin functions and lambda expressions. It explains that lambda expressions can be passed immediately as expressions or defined separately as functions. It also discusses that using higher-order functions can introduce runtime overhead which can be eliminated by inlining lambda expressions. Finally, it provides an example of an inline fun that demonstrates inlining and non-inlining of lambda expressions.
1 kotlin vs. java: some java issues addressed in kotlinSergey Bandysik
Kotlin addresses several issues in Java by controlling null references in the type system, eliminating raw types, making arrays invariant, defining proper function types, allowing use-site variance without wildcards, and removing checked exceptions. It fixes null references by allowing nullable types and non-null types, provides null-safe calls and operators like Elvis and safe casts, and filters nulls from collections.
The key difference between Java and Kotlin is given with details. Java is great and highly accepted across platforms, but its getting old.
Why is Kotlin taking so much preference and why should one prefer Kotlin? All the details are explained here.
Presented on 27th September 2017 to a joint meeting of 'Cork Functional Programmers' and the 'Cork Java Users Group'
Based on the Kotlin Language programming course from Instil. For more details see https://instil.co/courses/kotlin-development/
Category theory concepts such as objects, arrows, and composition directly map to concepts in Scala. Objects represent types, arrows represent functions between types, and composition represents function composition. Scala examples demonstrate how category theory diagrams commute, with projection functions mapping to tuple accessors. Thinking in terms of interfaces and duality enriches both category theory and programming language concepts. Learning category theory provides a uniform way to reason about programming language structures and properties of data types.
Some notes about programming in Scala: it covers Scala syntax and semantics, programming techniques, idioms, patterns. Many Scala features are introduced, from basic to intermediate and advanced. These are not introductory notes, but they assume a working knowledge with some other programming language (Java, C#, C++), object-oriented programming (OOP) concepts, and functional programming (FP) concepts.
Some key features of Scala include:
1. It allows blending of functional programming and object-oriented programming for more concise and powerful code.
2. The static type system allows for type safety while maintaining expressiveness through type inference, implicits, and other features.
3. Scala code interoperates seamlessly with existing Java code and libraries due to its compatibility with the JVM.
Esoft Metro Campus - Diploma in Web Engineering - (Module VII) Advanced PHP Concepts
(Template - Virtusa Corporate)
Contents:
Arrays
Indexed Arrays
Associative Arrays
Multidimensional arrays
Array Functions
PHP Objects and Classes
Creating an Object
Properties of Objects
Object Methods
Constructors
Inheritance
Method overriding
PHP Strings
printf() Function
String Functions
PHP Date/Time Functions
time() Function
getdate() Function
date() Function
mktime() function
checkdate() function
PHP Form Handling
Collecting form data with PHP
GET vs POST
Data validation against malicious code
Required fields validation
Validating an E-mail address
PHP mail() Function
Using header() function to redirect user
File Upload
Processing the uploaded file
Check if File Already Exists
Limit File Size
Limit File Type
Check if image file is an actual image
Uploading File
Cookies
Sessions
https://www.dmdiploma.com/studymaterial?id=5/python-for-data-science
This Python course provides a beginner-friendly introduction to Python for Data Science.
Well-architected libraries for functional programming are at once immensely beautiful and practical. They are simple but extraordinarily powerful, helping users solve their problems by snapping together Lego-like building blocks, each of which has just one purpose. Yet, there is a surprising dearth of material on how developers can construct their own well-architected functional code. Many functional programming tutorials talk discuss type safety and making illegal states unrepresentable, but few speak on the subject of good functional interface design.
In this presentation, John A. De Goes takes to the stage to discuss a nebulous and underrated tool in the arsenal of every functional programmer. Called *orthogonality*, this tool allows programmers to craft the building blocks of their functional code at "right angles", so so they can be reasoned about simply and composed predictably to solve complex problems. John introduces the concept of orthogonality, looking at its geometric and algebraic origins, presents a way to measure orthogonality, and then walks through a number of interface examples, comparing non-orthogonal designs with orthogonal ones.
By the end of the session, attendees should have a newfound appreciation for how important orthogonality is to constructing good functional interfaces, and they should develop the early stages of an intuition about how to slice up a complex problem into core, single-purpose, composable building blocks.
Kotlin advanced - language reference for android developersBartosz Kosarzycki
StxNext Lightning Talks - Mar 11, 2016
Kotlin Advanced - language reference for Android developers
This presentation contains the second talk on Kotlin language we had at STXNext. We try go deeper into language specifics and look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
We present real-world example based on Stx-Insider project written in Kotlin which incorporates Dagger 2, Kotterknife, Retrofit2 and is composed of 5+ Activities.
Full agenda
Live templates
Enum translation
Calling extension functions from Kotlin/Java
Constructors with backing fields
Warnings
F-bound polymorphism
Variance (Covariance/Contravariance)
Variance comparison in Kotlin/Java/Scala
Annotation processing - KAPT
SAM conversions
Type equality
Lambda vs Closure
Reified generics
Fluent interfaces
Infix notation
Static extension methods in Kotlin
Generic types
Sealed classes
Dokka - documentation in Kotlin
J2K converter
Real-world example
Reflection
Presentation is accompanied with an example project (StxInsider):
https://github.com/kosiara/stx-insider
The document provides an introduction to the Clojure programming language. It discusses that Clojure is a functional Lisp dialect that runs on the Java Virtual Machine. It extends the principle of code-as-data to include maps and vectors in addition to lists. The document also provides an overview of Clojure's core data structures, functions, concurrency features like atoms and agents, and how to get started with Clojure.
This document provides an introduction and overview of the Kotlin programming language. It begins with an agenda and quote about Kotlin being a good choice for Spring applications. The remainder of the document covers what Kotlin is, its main features like type inference, functional programming support, interoperability with Java, and language concepts like properties, classes, inheritance, interfaces, functions, collections and more. Code examples are provided to illustrate many of the language features. Resources for learning more about Kotlin are listed at the end.
Let's make a contract: the art of designing a Java APIMario Fusco
The document discusses best practices for designing Java APIs. It emphasizes making APIs intuitive, consistent, discoverable and easy to use. Some specific tips include using static factories to create objects, promoting fluent interfaces, using the weakest possible types, supporting lambdas, avoiding checked exceptions and properly managing resources using try-with-resources. The goal is to design APIs that are flexible, evolvable and minimize surprises for developers.
C# 3.0 introduces many features common in functional programming languages like generics, first-class functions, lambda expressions, and type inference. However, C# retains its object-oriented roots, and some features like datatypes and laziness remain more fully realized in pure functional languages. While C# supports programming in a functional style, its performance characteristics and lack of optimizations mean it may not be a serious competitor to ML and Haskell for functional programming tasks.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
This document discusses type classes in Scala and Haskell. It provides a recap of implicits in Scala, including implicit parameters, conversions, and views. It then introduces type class concepts and examples from the Scala standard library like Ordering and Numeric. It explains how to define a Printable type class and instances for types like Int and Cat. It discusses improved designs using companion objects and implicit classes. Finally, it covers where to define type class instances, such as for standard types in the companion object and domain types in their package.
Swift is a new programming language that is statically typed, multi-paradigm, and designed to work with Cocoa and Cocoa Touch. It features modern language elements like optionals, generics, closures, and pattern matching. Swift code is compiled to native executables making it performant, and it is designed to bridge seamlessly with Objective-C and Cocoa allowing existing iOS and OS X apps to migrate code over.
Kotlin is a concise, safe, and statically typed programming language that compiles to JVM bytecode and JavaScript. It focuses on interoperability with Java and solves many Java pitfalls. Kotlin removes verbosity like semicolons and replaces "extends" and "implement" with a colon. Functions are defined with the "fun" keyword and return types follow. Properties are treated like fields. Kotlin avoids null references through null safety features like the safe call operator and non-null assertion operator. When expressions replace switch statements. Extension functions can extend existing classes without subclassing.
An invited talk by Xavier Leroy explaining the current state of OCaml at the OCaml Users and Developers Workshop 2014. http://ocaml.org/meetings/ocaml/2014/
All Aboard The Scala-to-PureScript Express!John De Goes
Many Scala programmers have embraced functional programming, but the syntax and semantics of programming languages in the Haskell family remains a mystery. In this talk, Scala developers (and to some extent, Java developers) will see how the types, data structures, traits / interfaces, packages, and so forth translate into their PureScript counterparts.
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
The document discusses functional programming concepts like higher-order functions, function composition, currying, and lazy evaluation. It provides examples of implementing strategies like converting between units using functions and creating streams of prime numbers lazily to avoid stack overflows. Tail call optimization is mentioned as a way to avoid stack overflows with recursive functions.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
The Jetbrain's Kotlin language cheat sheet, created by ekito and launched for the Toulouse's devfest - https://www.ekito.fr/people/kotlin-cheat-sheet/
This paper helps you keep the main feature of the Kotlin language, under the hand. Just download it & print it !
Qcon2011 functions rockpresentation_scalaMichael Stal
Scala functions provide powerful ways to decompose problems and harness the benefits of functional programming. The presentation introduces core concepts of functional programming using Scala as an example language, highlighting how Scala combines object-oriented and functional programming. It presents benefits like immutability, higher-order functions, and improved concurrency while avoiding past performance issues through modern virtual machines and libraries.
Esoft Metro Campus - Diploma in Web Engineering - (Module VII) Advanced PHP Concepts
(Template - Virtusa Corporate)
Contents:
Arrays
Indexed Arrays
Associative Arrays
Multidimensional arrays
Array Functions
PHP Objects and Classes
Creating an Object
Properties of Objects
Object Methods
Constructors
Inheritance
Method overriding
PHP Strings
printf() Function
String Functions
PHP Date/Time Functions
time() Function
getdate() Function
date() Function
mktime() function
checkdate() function
PHP Form Handling
Collecting form data with PHP
GET vs POST
Data validation against malicious code
Required fields validation
Validating an E-mail address
PHP mail() Function
Using header() function to redirect user
File Upload
Processing the uploaded file
Check if File Already Exists
Limit File Size
Limit File Type
Check if image file is an actual image
Uploading File
Cookies
Sessions
https://www.dmdiploma.com/studymaterial?id=5/python-for-data-science
This Python course provides a beginner-friendly introduction to Python for Data Science.
Well-architected libraries for functional programming are at once immensely beautiful and practical. They are simple but extraordinarily powerful, helping users solve their problems by snapping together Lego-like building blocks, each of which has just one purpose. Yet, there is a surprising dearth of material on how developers can construct their own well-architected functional code. Many functional programming tutorials talk discuss type safety and making illegal states unrepresentable, but few speak on the subject of good functional interface design.
In this presentation, John A. De Goes takes to the stage to discuss a nebulous and underrated tool in the arsenal of every functional programmer. Called *orthogonality*, this tool allows programmers to craft the building blocks of their functional code at "right angles", so so they can be reasoned about simply and composed predictably to solve complex problems. John introduces the concept of orthogonality, looking at its geometric and algebraic origins, presents a way to measure orthogonality, and then walks through a number of interface examples, comparing non-orthogonal designs with orthogonal ones.
By the end of the session, attendees should have a newfound appreciation for how important orthogonality is to constructing good functional interfaces, and they should develop the early stages of an intuition about how to slice up a complex problem into core, single-purpose, composable building blocks.
Kotlin advanced - language reference for android developersBartosz Kosarzycki
StxNext Lightning Talks - Mar 11, 2016
Kotlin Advanced - language reference for Android developers
This presentation contains the second talk on Kotlin language we had at STXNext. We try go deeper into language specifics and look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
We present real-world example based on Stx-Insider project written in Kotlin which incorporates Dagger 2, Kotterknife, Retrofit2 and is composed of 5+ Activities.
Full agenda
Live templates
Enum translation
Calling extension functions from Kotlin/Java
Constructors with backing fields
Warnings
F-bound polymorphism
Variance (Covariance/Contravariance)
Variance comparison in Kotlin/Java/Scala
Annotation processing - KAPT
SAM conversions
Type equality
Lambda vs Closure
Reified generics
Fluent interfaces
Infix notation
Static extension methods in Kotlin
Generic types
Sealed classes
Dokka - documentation in Kotlin
J2K converter
Real-world example
Reflection
Presentation is accompanied with an example project (StxInsider):
https://github.com/kosiara/stx-insider
The document provides an introduction to the Clojure programming language. It discusses that Clojure is a functional Lisp dialect that runs on the Java Virtual Machine. It extends the principle of code-as-data to include maps and vectors in addition to lists. The document also provides an overview of Clojure's core data structures, functions, concurrency features like atoms and agents, and how to get started with Clojure.
This document provides an introduction and overview of the Kotlin programming language. It begins with an agenda and quote about Kotlin being a good choice for Spring applications. The remainder of the document covers what Kotlin is, its main features like type inference, functional programming support, interoperability with Java, and language concepts like properties, classes, inheritance, interfaces, functions, collections and more. Code examples are provided to illustrate many of the language features. Resources for learning more about Kotlin are listed at the end.
Let's make a contract: the art of designing a Java APIMario Fusco
The document discusses best practices for designing Java APIs. It emphasizes making APIs intuitive, consistent, discoverable and easy to use. Some specific tips include using static factories to create objects, promoting fluent interfaces, using the weakest possible types, supporting lambdas, avoiding checked exceptions and properly managing resources using try-with-resources. The goal is to design APIs that are flexible, evolvable and minimize surprises for developers.
C# 3.0 introduces many features common in functional programming languages like generics, first-class functions, lambda expressions, and type inference. However, C# retains its object-oriented roots, and some features like datatypes and laziness remain more fully realized in pure functional languages. While C# supports programming in a functional style, its performance characteristics and lack of optimizations mean it may not be a serious competitor to ML and Haskell for functional programming tasks.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
This document discusses type classes in Scala and Haskell. It provides a recap of implicits in Scala, including implicit parameters, conversions, and views. It then introduces type class concepts and examples from the Scala standard library like Ordering and Numeric. It explains how to define a Printable type class and instances for types like Int and Cat. It discusses improved designs using companion objects and implicit classes. Finally, it covers where to define type class instances, such as for standard types in the companion object and domain types in their package.
Swift is a new programming language that is statically typed, multi-paradigm, and designed to work with Cocoa and Cocoa Touch. It features modern language elements like optionals, generics, closures, and pattern matching. Swift code is compiled to native executables making it performant, and it is designed to bridge seamlessly with Objective-C and Cocoa allowing existing iOS and OS X apps to migrate code over.
Kotlin is a concise, safe, and statically typed programming language that compiles to JVM bytecode and JavaScript. It focuses on interoperability with Java and solves many Java pitfalls. Kotlin removes verbosity like semicolons and replaces "extends" and "implement" with a colon. Functions are defined with the "fun" keyword and return types follow. Properties are treated like fields. Kotlin avoids null references through null safety features like the safe call operator and non-null assertion operator. When expressions replace switch statements. Extension functions can extend existing classes without subclassing.
An invited talk by Xavier Leroy explaining the current state of OCaml at the OCaml Users and Developers Workshop 2014. http://ocaml.org/meetings/ocaml/2014/
All Aboard The Scala-to-PureScript Express!John De Goes
Many Scala programmers have embraced functional programming, but the syntax and semantics of programming languages in the Haskell family remains a mystery. In this talk, Scala developers (and to some extent, Java developers) will see how the types, data structures, traits / interfaces, packages, and so forth translate into their PureScript counterparts.
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
The document discusses functional programming concepts like higher-order functions, function composition, currying, and lazy evaluation. It provides examples of implementing strategies like converting between units using functions and creating streams of prime numbers lazily to avoid stack overflows. Tail call optimization is mentioned as a way to avoid stack overflows with recursive functions.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
The Jetbrain's Kotlin language cheat sheet, created by ekito and launched for the Toulouse's devfest - https://www.ekito.fr/people/kotlin-cheat-sheet/
This paper helps you keep the main feature of the Kotlin language, under the hand. Just download it & print it !
Qcon2011 functions rockpresentation_scalaMichael Stal
Scala functions provide powerful ways to decompose problems and harness the benefits of functional programming. The presentation introduces core concepts of functional programming using Scala as an example language, highlighting how Scala combines object-oriented and functional programming. It presents benefits like immutability, higher-order functions, and improved concurrency while avoiding past performance issues through modern virtual machines and libraries.
This document provides an introduction to the Scala programming language. It discusses what Scala is, how to get started, basic concepts like mutability and functions, and Scala features like classes, traits, pattern matching, and collections. Scala combines object-oriented and functional programming. It runs on the Java Virtual Machine and is compatible with Java. The document provides code examples to demonstrate Scala concepts and features.
The document discusses operator overloading in Kotlin using the example of a Coin enum and Wallet class. It defines a Coin enum with values for common coins (PENNY, NICKEL, etc) that each have a cents value. A Wallet class is defined with a plusAssign operator function that allows adding Coin values to the wallet amount. Examples are shown incrementing a wallet variable by adding Coin values like QUARTER to demonstrate operator overloading.
The Scala Programming Language was presented with the goals of creating a language that better supports component software and unifies object-oriented and functional programming. Scala is statically typed and supports both object-oriented and functional programming paradigms through features like traits, views, and variance annotations. It also aims to improve on concepts from Java and other languages through ideas like mixins and compound types.
The Kotlin Programming Language, Svetlana IsakovaVasil Remeniuk
The document discusses the Kotlin programming language. It describes Kotlin as a modern, statically typed, object-oriented language that compiles to JVM bytecode or JavaScript. Kotlin was developed by JetBrains as an open source language intended for industrial use. The document then covers various features of Kotlin like its handling of null safety using nullable types, extension functions, smart casts for pattern matching, and approach to collection transformations.
This document provides an overview of Scala fundamentals including:
- Scala is a programming language for the JVM that supports both object-oriented and functional paradigms.
- It defines variables, values, lazy values, functions, types, classes, objects, traits, and higher-order functions.
- Classes can extend other classes and traits, allowing for multiple inheritance. Objects are used as singletons.
- Functional concepts like immutability, anonymous functions, and higher-order functions are supported.
Kotlin is a statically typed programming language that runs on the Java Virtual Machine and is fully interoperable with Java. It was developed by JetBrains as an alternative to Java for Android development, with improvements like null safety, lambdas, and concise syntax. Kotlin aims to be a safer language than Java by eliminating NullPointerExceptions and adding features like data classes, extensions, and higher-order functions. These features allow for more readable, concise code compared to Java.
Kotlin: A pragmatic language by JetBrainsJigar Gosar
A pragmatic language for JVM and Android.
Combines OO and functional features.
Focused on interoperability, safety, clarity, tooling support.
Open Source.
Works everywhere where Java works.
Key focus on interoperability and seamless support for mixed Java+Kotlin projects.
This document provides an overview of Scala for Java developers. It covers Scala basics like running on the JVM and supporting functional programming. It also summarizes key Scala syntax like type declarations, expressions, loops, functions, classes, traits, objects, and collections. The document compares Java and Scala concepts and provides resources to learn more about Scala.
The document summarizes several Java 5 features including generics, enhanced for loops, autoboxing/unboxing, typesafe enums, varargs, static imports, and annotations. It provides examples and explanations of each feature.
An introduction to Kotlin for advanced Android beginners, covering command-line compilation of Kotlin files, conditional logic, val/var, basic functions, higher order functions, recursion.
In this PDF you can learn about Kotlin Basic as well as Intermediate part. As also you can develop the android apps and publish in a google play store.
Scala is a multi-paradigm language that runs on the JVM and interoperates with Java code and libraries. It combines object-oriented and functional programming by allowing functions to be treated as objects and supports features like traits, pattern matching, and immutable data structures. The Scala compiler infers types and generates boilerplate code like getters/setters, making development more productive compared to Java. While Scala has a learning curve, it allows a more concise and scalable language for building applications.
Android Developer Group Poznań - Kotlin for Android developers
STXInsider example project in Kotlin:
https://github.com/kosiara/stx-insider
Kotlin - one of the popular programming languages built on top of Java that runs on JVM. Thanks to JetBrains support and excellent IDE integration, it’s an ideal choice for Android development. 100% Java compatibility, interoperability and no runtime overhead is just the beginning of a long list of strengths. Kotlin is supposed to be a subset of SCALA, has clear benefits for developers on one hand and keeps short compile times on the other.
As a mobile team we got interested in Kotlin a few months before its final release which gave us time to test it thoroughly before production use. The language has some clear advantages for an Android programmer - it enables migration from Java projects that have been under development for some time already. Java&Kotlin coexistence simplifies Kotlin introduction as only new functionality is written in JetBrain’s new language leaving all the legacy code untouched.
Transitioning gives the developer an opportunity to use lambdas, new syntax for data objects, extension functions to easily expand Android SDK’s classes functionality and infix notation to write DSL-like structures. Almost all the libraries you use today will work with Kotlin thanks to 100% Java compatibility. The same is true for Android SDK classes - all of them will seamlessly work with the new programming language. Kotlin gives you more choice when it comes to reflection, creating documentation and being null-pointer safe. Android works great with it out of the box so you won’t need to change your development habits.
Our production project in Kotlin turned out to be a success after 4 months of development. We had 0 bugs related to Kotlin as a programming language. Our code footprint is almost 30% smaller thanks to JetBrain’s, we benefit from nullpointer safety, closures, translated enums, data objects and use infix notation for logging and displaying Snackbars.
===========
In this presentation you'll find basic use cases, syntax, structures and patterns. Later on Kotlin is presented in Android context. Simple project structure, imports and Kotlin usage with Android SDK is explained. In the end cost of Kotlin compilation is presented and the language is compared to SCALA and SWIFT.
We look at the positive impact new syntax can have on boilerplate removal and readability improvement.
Kotlin really shines in Android development when one looks at “Enum translation”, “Extension functions”, “SAM conversions”, “Infix notation”, “Closures” and “Fluent interfaces” applied to lists. The talk, however, compares language-specifics of Java & Kotlin in terms of “Type Variance”, “Generics” and “IDE tools” as well.
While Google is adding Kotlin as an official Android language, we're also expanding our research on this language. It’s developed by JetBrains, and the fact that these are the people behind a suite of IDEs, such as IntelliJ and ReSharper, really shines through in Kotlin. It’s pragmatic and concise and makes coding a satisfying and efficient experience.
Although Kotlin compiles to both JavaScript and soon machine code, I’ll focus on its prime environment, the JVM.
Please see my presentation to learn more!
Kotlin provides a modern, statically-typed, and expressive alternative to Java, offering null safety, coroutines for asynchronous programming, and a succinct, intuitive syntax.
This presentation will give an introduction to Kotlin, looking at various language features, how those features are utilized by the Kotlin Standard Library, and how they are implemented in performance-conscious ways.
This document discusses how Kotlin can help improve Android app quality by eliminating common issues like crashes and null pointer exceptions. It highlights Kotlin features like non-nullable types, the safe call operator, and extension functions. Kotlin offers improvements over Java like optional and collection APIs without nullability and verbosity issues. It also maintains full interoperability with Java while providing better tools for static analysis and debugging.
Similar to 2 kotlin vs. java: what java has that kotlin does not (20)
2. What Java has that Kotlin does not
— Checked exceptions
— Primitive types that are not classes
— Static members
— Non-private fields
— Wildcard-types
4. Exception Classes
All exception classes in Kotlin are descendants of the class Throwable
throw MyException("Hi There!")
try {
// some code
}
catch (e: SomeException) {
// handler
}
finally {
// optional finally block
}
5. Try is an expression
val a: Int? = try { parseInt(input) } catch (e: NumberFormatException) { null }
6. Checked Exceptions
Kotlin does not have checked exceptions
class StringBulder
Appendable append(CharSequence csq) throws IOException;
try {
log.append(message)
}
catch (IOException e) {
// Must be safe
}
7. The Nothing type
val s = person.name ?: throw IllegalArgumentException("Name required")
In your own code, you can use Nothing to mark a function that never returns:
fun fail(message: String): Nothing {
throw IllegalArgumentException(message)
}
val s = person.name ?: fail("Name required")
println(s) // 's' is known to be initialized at this point
val x = null // 'x' has type `Nothing?`
val l = listOf(null) // 'l' has type `List<Nothing?>
9. Basic Types
In Kotlin, everything is an object in the sense that we can call member functions
and properties on any variable
Some of the types can have a special internal representation - for example,
numbers, characters and booleans can be represented as primitive values at
runtime - but to the user they look like ordinary classes
10. Numbers
— no implicit widening conversions
for numbers
— literals are slightly different in
some cases
characters are not numbers in Kotlin
Type Bit width
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8
11. Literal Constants
— Decimals: 123
– Longs L: 123L
— Hexadecimals: 0x0F
— Binaries: 0b00001011
Octal literals are not supported
— Doubles by default: 123.5,
123.5e10
— Floats are tagged by f or F:
123.5f
12. Underscores in numeric literals (since 1.1)
val oneMillion = 1_000_000
val creditCardNumber = 1234_5678_9012_3456L
val socialSecurityNumber = 999_99_9999L
val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010
13. Representation
val a: Int = 10000
print(a === a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints
'false'!!!
val a: Int = 10000
print(a == a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA == anotherBoxedA) // Prints
'true'
14. Explicit Conversions
// Hypothetical code, does not actually compile:
val a: Int? = 1 // A boxed Int (java.lang.Integer)
val b: Long? = a // implicit conversion yields a boxed Long (java.lang.Long)
print(a == b) // Surprise! This prints "false" as Long's equals() check for other part to be Long
as well
val b: Byte = 1 // OK, literals are checked statically
val i: Int = b // ERROR
val i: Int = b.toInt() // OK: explicitly widened
15. Number type supports the following conversions:
— toByte(): Byte
— toShort(): Short
— toInt(): Int
— toLong(): Long
— toFloat(): Float
— toDouble(): Double
— toChar(): Char
16. Characters
Characters are represented by the type Char
They can not be treated directly as numbers
fun check(c: Char) {
if (c == 1) { // ERROR: incompatible types
// ...
}
}
Character literals go in single quotes: '1'
17. Booleans
The type Boolean represents booleans, and has two values: true and false
Built-in operations on booleans include
— || – lazy disjunction
— && – lazy conjunction
— ! - negation
18. Arrays
Arrays in Kotlin are represented by
the Array class, that has get and
set functions (that turn into [] by
operator overloading conventions),
and size property, along with a few
other useful member functions:
class Array<T> private constructor() {
val size: Int
operator fun get(index: Int): T
operator fun set(index: Int, value: T): Unit
operator fun iterator(): Iterator<T>
// ...
}
19. Arrays
Note: unlike Java, arrays in Kotlin are
invariant. This means that Kotlin does
not let us assign an Array<String>
to an Array<Any>, which prevents a
possible runtime failure (but you can
use Array<out Any>
Kotlin also has specialized classes to
represent arrays of primitive types
without boxing overhead: ByteArray,
ShortArray, IntArray and so on.
20. Strings
Strings are represented by the type String
Strings are immutable
Elements of a string are characters that can be accessed by the indexing
operation: s[i]
A string can be iterated over with a for-loop:
for (c in str) {
println(c)
}
21. String Literals
val s = "Hello, world!n"
val text = """
for (c in "foo")
print(c)
"""
val text = """
|Tell me and I forget.
|Teach me and I remember.
|Involve me and I learn.
|(Benjamin Franklin)
""".trimMargin()
22. String Templates
val i = 10
val s = "i = $i" // evaluates to "i = 10"
val s = "abc"
val str = "$s.length is ${s.length}" // evaluates to "abc.length is 3"
val price = """
${'$'}9.99
"""
24. Companion Objects
In Kotlin, unlike Java or C#, classes do not have static methods
In most cases, it's recommended to simply use package-level functions instead
class MyClass {
companion object {
}
}
val x = MyClass.Companion
25. Object declarations
If you need to write a function that can be called without having a class instance
but needs access to the internals of a class (for example, a factory method), you
can write it as a member of an object declaration inside that class
object DataProviderManager {
fun registerDataProvider(provider: DataProvider) {
// ...
}
val allDataProviders: Collection<DataProvider>
get() = // ...
}
27. Declaring Properties
Classes in Kotlin can have properties
These can be declared:
— as mutable, using the var
keyword
— read-only using the val keyword
class Address {
var name: String = ...
var street: String = ...
var state: String? = ...
var zip: String = ...
}
fun copyAddress(address: Address): Address {
val result = Address()
result.name = address.name
result.street = address.street
// ...
return result
}
28. Getters and Setters
var <propertyName>[: <PropertyType>] [= <property_initializer>]
[<getter>]
[<setter>]
The initializer, getter and setter are optional
Property type is optional if it can be inferred from the initializer (or from the getter
return type, as shown below)
29. it starts with val instead of var
does not allow a setter
val simple: Int? // has type Int, default getter, must be initialized in constructor
val inferredType = 1 // has type Int and a default getter
val isEmpty: Boolean
get() = this.size == 0
var stringRepresentation: String
get() = this.toString()
set(value) {
setDataFromString(value) // parses the string and assigns values to other properties
}
Read-only property
30. Backing Fields
Classes in Kotlin cannot have fields
var counter = 0 // the initializer value is written directly to the backing field
set(value) {
if (value >= 0) field = value
}
The field identifier can only be used in the accessors of the property
For example, in the following case there will be no backing field:
val isEmpty: Boolean
get() = this.size == 0
31. Backing Properties
If you want to do something that does not fit into this "implicit backing field"
scheme, you can always fall back to having a backing property:
private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
get() {
if (_table == null) {
_table = HashMap() // Type parameters are inferred
}
return _table ?: throw AssertionError("Set to null by another thread")
}
In all respects, this is just the same as in Java since access to private properties
with default getters and setters is optimized so that no function call overhead is
introduced
32. Compile-Time Constants
Properties the value of which is known at compile time can be marked as compile
time constants using the const modifier. Such properties need to fulfil the
following requirements:
— Top-level or member of an object
— Initialized with a value of type String or a primitive type
— No custom getter
Such properties can be used in annotations:
const val SUBSYSTEM_DEPRECATED: String = "This subsystem is deprecated"
@Deprecated(SUBSYSTEM_DEPRECATED) fun foo() { ... }
33. Late-Initialized Properties
To handle this case, you can mark
the property with the lateinit
modifier:
public class MyTest {
lateinit var subject: TestSubject
@SetUp fun setup() {
subject = TestSubject()
}
@Test fun test() {
subject.method() // dereference
directly
}
}
The modifier can only be used on var
properties declared inside the body of
a class (not in the primary
constructor), and only when the
property does not have a custom
getter or setter
The type of the property must be
non-null, and it must not be a
primitive type
35. Generics
class Box<T>(t: T) {
var value = t
}
To create an instance of such a class, we need to provide the type arguments:
val box: Box<Int> = Box<Int>(1)
36. Variance
One of the most tricky parts of Java's type system is wildcard types
And Kotlin doesn't have any
Instead, it has two other things:
● declaration-site variance
● type projections
37. Declaration-site variance (variance annotation out)
interface Source<T> {
T nextT();
}
void demo(Source<String> strs) {
Source<Object> objects = strs; // !!! Not
allowed in Java
// ...
}
Source<? extends Object>
abstract class Source<out T> {
abstract fun nextT(): T
}
fun demo(strs: Source<String>) {
val objects: Source<Any> = strs // This
is OK, since T is an out-parameter
// ...
}
38. Declaration-site variance (variance annotation in)
abstract class Comparable<in T> {
abstract fun compareTo(other: T): Int
}
fun demo(x: Comparable<Number>) {
x.compareTo(1.0) // 1.0 has type Double, which is a subtype of Number
// Thus, we can assign x to a variable of type Comparable<Double>
val y: Comparable<Double> = x // OK!
}
39. Use-site variance: Type projections
class Array<T>(val size: Int) {
fun get(index: Int): T { /* ... */ }
fun set(index: Int, value: T) { /* ... */ }
}
fun copy(from: Array<Any>, to: Array<Any>) {
assert(from.size == to.size)
for (i in from.indices)
to[i] = from[i]
}
val ints: Array<Int> = arrayOf(1, 2, 3)
val any = Array<Any>(3) { "" }
copy(ints, any) // Error: expects (Array<Any>,
Array<Any>).
fun copy(from: Array<out Any>, to: Array<Any>) {
// ...
}
40. Generic functions
Not only classes can have type parameters. Functions can, too:
fun <T> singletonList(item: T): List<T> {
// ...
}
fun <T> T.basicToString() : String { // extension function
// ...
}
To call a generic function, specify the type arguments at the call site after the
name of the function:
val l = singletonList<Int>(1)