Tuesday, September 12, 2017

Getting Started with React: A Beginner’s Guide

In this guide, I'll show you the fundamental concepts of React by taking you through a practical, step-by-step tutorial on how to create a simple Message App using React. I'll assume you have no previous knowledge of React. However, you'll need at least to be familiar with modern JavaScript and NodeJS.

React is a remarkable JavaScript library that's taken the development community by storm. In a nutshell, it's made it easier for developers to build interactive user interfaces for web, mobile and desktop platforms. One of its best features is its freedom from the problematic bugs inherent in MVC frameworks, where inconsistent views is a recurring problem for big projects. Today, thousands of companies worldwide are using React, including big names such as Netflix and AirBnB. React has become immensely popular, such that a number of apps have been ported to React --- including WhatsApp, Instagram and Dropbox.

Prerequisites

As mentioned, you need some experience in the following areas:

On your machine, you'll need:

If you'd like to take a look first at the completed project that's been used in this guide, you can access it via GitHub.

[affiliate-section title="Recommended Courses"][affiliate-card title="The Best Way to Learn React for Beginners" affiliatename="Wes Bos" text="A step-by-step training course to get you building real world React.js + Firebase apps and website components in a couple of afternoons. Use coupon code 'SITEPOINT' at checkout to get 25% off." url="http://ift.tt/2tF1ast" imageurl="http://ift.tt/2y2HI7v"][/affiliate-section]

What is React?

React is a JavaScript library for building UI components. Unlike more complete frameworks such as Angular or Vue, React deals only with the view layer. Hence, you'll need additional libraries to handle things such as data flow, routing, authentication etc. In this guide, we'll focus on what React can do.

Building a React project involves creating one or more React components that can interact with each other. A React component is simply a JavaScript class that requires the render function to be declared. The render function simply outputs HTML code, which is implemented using either JSX or JavaScript code. A React component may also require additional functions for handling data, actions and lifecyle events.

React components can further be categorized into containers/stateful components and stateless components. A stateless component's work is simply to display data that it receives from its parent React component. It can also receive events and inputs, which it passes up to its parent to handle. A React container or stateful component does the work of rendering one or more child components. It fetches data from external sources and feeds it to its child components. It also receives inputs and events from them in order to initiate actions.

Understanding the React DOM

Before we get to coding, you need to be aware that React uses a Virtual DOM to handle page rendering. If you're familiar with jQuery, you know that it can directly manipulate a web page via the HTML DOM. In a lot of use cases, this direct interaction poses little to no problems. However, for certain cases, such as the running of a highly interactive, real-time web application, performance often takes a huge hit.

To counter this, the concept of the Virtual DOM was invented, and is currently being applied by many modern UI frameworks including React. Unlike the HTML DOM, the Virtual DOM is much easier to manipulate, and is capable of handling numerous operations in milliseconds without affecting page performance. React periodically compares the Virtual DOM and the HTML DOM. It then computes a diff, which it applies to the HTML DOM to make it match the Virtual DOM. This way, React does its best to ensure your application is rendered at a consistent 60 frames per second, meaning that users experience little or no lag.

Enough chitchat! Let's get our hands dirty …

Start a Blank React Project

As per the prerequisites, I assume you already have a NodeJS environment setup. Let's first install or update npm to the latest version.

$ npm i -g npm

Next, we're going to install a tool, Create React App, that will allow us to create our first React project:

$ npm i -g create-react-app

Navigate to your project's root directory and create a new React project using the tool we just installed:

$ create-react-app message-app

…
Success! Created message-app at /home/mike/Projects/github/message-app
Inside that directory, you can run several commands:

  yarn start
    Starts the development server.

  yarn build
    Bundles the app into static files for production.

  yarn test
    Starts the test runner.

  yarn eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd message-app
  yarn start

Happy hacking!

Depending on the speed of your internet connection, this might take a while to complete if this is your first time running the create-react-app command. A bunch of packages gets installed along the way, which are needed to set up a convenient development environment --- including a web server, compiler and testing tools.

Navigate to the newly created message-app folder and open the package.json file.

{
  "name": "message-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-scripts": "1.0.12"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Surprise! You expected to see a list of all those packages listed as dependencies, didn't you? Create React App is an amazing tool that works behind the scenes. It creates a clear separation between your actual code and the development environment. You don't need to manually install Webpack to configure your project. Create React App has already done it for you, using the most common options.

Let's do a quick test run to ensure our new project has no errors:

$ yarn start

Starting development server…
Compiled successfully!

You can now view message-app in the browser.

  Local:            http://localhost:3000/
  On Your Network:  http://10.0.2.15:3000/

Note that the development build is not optimized.
To create a production build, use yarn build.

If you don't have Yarn, just substitute with npm like this: npm start. For the rest of the article, use npm in place of yarn if you haven't installed it.

Your default browser should launch automatically, and you should get a screen like this:

Create React App

One thing to note is that Create React App supports hot reloading. This means any changes we make on the code will cause the browser to automatically refresh. For now, let's first stop the development server by pressing Ctrl + C. This step isn't necessary, I'm just showing you how to kill the development server. Once the server has stopped, delete everything in the src folder. We'll create all the code from scratch so that you can understand everything inside the src folder.

Introducing JSX Syntax

Inside the src folder, create an index.js file and place the following code in it:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(<h1>Hello World</h1>, document.getElementById('root'));

Start the development server again using yarn start or npm start. Your browser should display the following content:

Hello React

This is the most basic "Hello World" React example. The index.js file is the root of your project where React components will be rendered. Let me explain how the code works:

  • Line 1: React package is imported to handle JSX processing
  • Line 2: ReactDOM package is imported to render React components.
  • Line 4: Call to render function
    • <h1>Hello World</h1>: a JSX element
    • document.getElementById('root'): HTML container

The HTML container is located in public/index.html file. On line 28, you should see <div id="root"></div>. This is known as the root DOM because everything inside it will be managed by the React DOM.

JSX (JavaScript XML) is a syntax expression that allows JavaScript to use tags such as <div>, <h1>, <p>, <form>, and <a>. It does look a lot like HTML, but there are some key differences. For example, you can't use a class attribute, since it's a JavaScript keyword. Instead, className is used in its place. Also, events such as onclick are spelled onClick in JSX. Let's now modify our Hello World code:

const element = &lt;div&gt;Hello World&lt;/div&gt;;

ReactDOM.render(element, document.getElementById('root'));

I've moved out the JSX code into a variable named element. I've also replaced the h1 tags with div. For JSX to work, you need to wrap your elements inside a single parent tag. This is necessary for JSX to work. Take a look at the following example:

const element = &lt;span&gt;Hello,&lt;/span&gt; &lt;span&gt;Jane&lt;/span;

The above code won't work. You'll get a syntax error telling you must enclose adjacent JSX elements in an enclosing tag. Basically, this is how you should enclose your elements:

const element = &lt;div&gt;
    &lt;span&gt;Hello, &lt;/span&gt;
    &lt;span&gt;Jane&lt;/span&gt;
  &lt;/div&gt;;

How about evaluating JavaScript expressions in JSX? Simple, just use curly braces like this:

const name = "Jane";
const element = &lt;p&gt;Hello, {name}&lt;/p&gt;

… or like this:

const user = {
  firstName: "Jane",
  lastName: "Doe"
}
const element = &lt;p&gt;Hello, {user.firstName} {user.lastName}&lt;/p&gt;

Update your code and confirm that the browser is displaying "Hello, Jane Doe". Try out other examples such as { 5 + 2 }. Now that you've got the basics of working with JSX, let's go ahead and create a React component.

Continue reading %Getting Started with React: A Beginner’s Guide%


by Michael Wanyoike via SitePoint

How to Learn React: Everything You Need to Get Started

React is a JavaScript library, originally built by developers at Facebook, for building fast user interfaces. If you’re dipping your toe into the React waters, or if your React development journey is picking up speed, it can be hard to stay across the fundamentals, techniques, tools and tricks – so we’ve created this guide to […]

Continue reading %How to Learn React: Everything You Need to Get Started%


by Adam Roberts via SitePoint

The Digital World – Just How Connected Are We In 2017? - #infographic

Since 2016 the world population has grown by 1.1%, of the 7.47 billion people on Earth, 50% are active internet users and somewhat surprisingly only 46% are active mobile users. Desktops and laptops are still the most prevalent method of connecting to the internet, by 2018 mobile devices will...

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Irfan Ahmad via Digital Information World

How to find anything on the dark web [video]

In recent years, the media has been abuzz with the dark web, and how this technology has made it even easier for criminals to partake in illegal activities; but, what is the dark web even, how do you get there, and what's on it? So, we brought Etay Maor, and IBM security specialist , to walk us...

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World

Exploring New Features in React 16

In this post, we're going to learn how to create a music player using some of the new features in React 16.

In implementing this music player, we’re going to learn about some of the changes in React 16. There are quite a few changes, so we won't cover all of them, but we’ll cover the ones that are important and that you can implement today. The album art comes from an album by a band called the Glass Animals. Since we can't legally stream the "Glass Animals" soundtrack, we've picked some royalty-free music to play in its place so we can get the full effect of the music player.

See the Pen React DailyUI - 009 - Music Player by Jack Oliver (@jackoliver) on CodePen.

The complete source for this post is also available on GitHub here.

To start the app, download the code, cd into the project directory and type:

npm install
npm start

State in a React Application

All React applications include a property called state that determines how and what components (and any data associated with those components) should be displayed.

Our music player has a state property that contains two important pieces of information: one variable that specifies whether the player is playing music --- the playing boolean --- and one variable that tracks the state of the current track --- the currentTrackIndex variable.

this.state = {
  playing: false,
  currentTrackIndex: 0
};

What is State?

When we refer to a component's state, we mean a snapshot of the instance of the component on the page.

React's components can define their own state, which we'll use in this post. When we use state in a React component, the component is said to be stateful. A React component can define its own state using a state property for handling stateful components, such as our music player.

As the user clicks the play, pause, next, and previous buttons, and the tracks in the player, our component will update its current state.

Props vs State

For React applications, it's important to understand the distinction between props and state. Our music player has two state variables that determine the way our application is displayed at a given point in time. The App component is our main component that drives the display of our child components --- the Controls component and the TrackList component. In order for these two components to receive information about the state of our application, the App component will pass information down as props to the children components. These props can then be used in the child component to display their pieces of the application correctly. Another important thing to understand is that every time our App component updates, our Controls component and TrackList component will be updated as well, because they rely on information from the App component.

Controls

Our Controls component is the first child of our App component. The Controls component is given two props: onClick and playing. The onClick prop allows us to pass down our handleClick function we've defined in the App component to the Controls component. When the user clicks one of the buttons in our Controls component, the handleClick function will get called. The playing prop allows the Controls component to know what the current state of the player is so we can properly render the play icon or the pause icon.

Let's explore how we render our buttons and handle clicks in our Controls component.

In our Controls component we have three important buttons:

  1. The << (previous) button --- an arrow icon pointing to the left --- which selects the previous track in the list
  2. The play/pause button which plays and pauses the music
  3. The >> (next) button --- an arrow icon pointing to the right --- which selects the next track in the list.

When each of these buttons is clicked, we call the click handler function that we passed in from the App component. Each of the buttons in our music player application has an id which will aid us in determining how a particular click should be handled.

In the internals of the handleClick function, we use a switch statement that uses the id of the button that was clicked --- e.target.id to determine how to handle the action from the button. In the next section, we'll take a look at what happens in each case of the switch statement.

The play button

When the play button is clicked, we'll need to update a few parts of our application. We'll need to switch the play icon to the pause icon. We'll also need to update the currentTrackIndex if it’s currently set to 0. In order to change these two parts of our application, we'll call setState, a function available to every React component.

The setState function is available to all React components, and it's how we update the state of our music player. The first argument in the setState function can either be an object or a function. If we're not relying on the current state of an application to calculate the next state, using an object as the first argument is a perfectly fine approach and looks like this: this.setState({currentState:'newState'}). In our case, we're relying on the current state of the application to determine the next state of our application, so we'll want to use a function. The React documentation indicates why this is important:

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

As React 16 turns on more of its features (including asynchronous rendering), this distinction will become more important to understand.

When the play button is clicked and we call setState, we pass in a function, because we're relying on the current value of the currentTrackIndex state variable. The first argument that's passed into the function is the previous state of our application, and the second argument is the current props. In our case, we just need the previous state of the application to determine the next state:

case "play":
  this.setState((state, props) => {
    let currentTrackIndex = state.currentTrackIndex;
    if (currentTrackIndex === 0) {
      currentTrackIndex = 1;
    }

Once we've set the currentTrackIndex properly based on the previous value of the currentTrackIndex, we then return an object of the values we want to update. In the case of the play button being clicked, we update our playing boolean to true and set the value of the currentTrackIndex:

return {
  playing: true,
  currentTrackIndex: currentTrackIndex
};

The second argument that's passed into the setState function is a callback function that's called after the setState function is completed. When the play button is clicked, and the state of our application is updated, we want to start playing the music. We pass in the this.playAudio function as the second argument to our setState function.

},this.playAudio);

When the playAudio button is called, we reference the audio tag and call the load and play functions available to us via the Web Audio API.

playAudio(){
  this.audioElement.load();
  this.audioElement.play();
}

ref to a DOM element

In order to reference the actual audio DOM element to play the audio, we'll need to use a special attribute available to all React components, the ref attribute. From the React documentation:

When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument.

In our situation, we add the ref attribute to our audio DOM element, and that allows us to play the audio for each track:

<audio ref={(audio)=>{this.audioElement = audio}} src={"/songs/"+this.state.currentTrackIndex+".mp3"}/>

The pause button

When the pause button is clicked, we call this.setState and set our playing boolean to false.

case "pause":
  this.setState({ playing: false },this.pauseAudio);
  break;

The second argument for our setState function call is our this.pauseAudio function, which references the audio element and calls the pause() function.

pauseAudio(){
  this.audioElement.pause();
}

The << (previous) button

When the << icon is clicked, the id of the previous button matches the "prev" case of the switch statement, so the code associated with the "prev" case is executed. In the "prev" case, we call this.setState() again with a function like we did for playing and pausing our application. This time, we use the previous value of currentTrackIndex to decrement the value and return an object to set currentTrackIndex to the new value.

case "prev":
  this.setState((state, props) => {
    let currentIndex = state.currentTrackIndex - 1;
    if (currentIndex <= 0) {
      return null;
    } else {
      return { playing:true,currentTrackIndex: currentIndex };
    }
  },this.playAudio);

Returning null from setState

One of the new changes in React 16 is that when we return null from a setState function, our application will not be re-rendered. Our track listing has 11 tracks available. If the user continues to click the << button, the currentTrackIndex will decrement until it gets to 0. Once it gets to 0, we no longer want to decrement the currentTrackIndex and we no longer need to re-render our application. We also do the same when our >> icon is clicked. If the currentTrackIndex is equal (or greater than) the number of tracks in our list (11), we return null from setState.

The >> (next) button

When the >> button is called, we have a similar functionality in place as the << button. Each time the user clicks >>, we increment the currentTrackIndex and we check that the currentTrackIndex is not greater than the length of the track list. If it is, we return null in our setState function call.

case "next":
  this.setState((state, props) => {
    let currentIndex = state.currentTrackIndex + 1;
    if (currentIndex > data.tracks.length) {
      return null;
    } else {
      return { playing:true,currentTrackIndex: currentIndex };
    }
  },this.playAudio);
  break;

Continue reading %Exploring New Features in React 16%


by Sophia Shoemaker via SitePoint

Kotlin From Scratch: More Fun With Functions

Kotlin is a modern programming language that compiles to Java bytecode. It is free and open source, and promises to make coding for Android even more fun.  

In the previous article, you learned about packages and basic functions in Kotlin. Functions are at the heart of Kotlin, so in this post we'll look more closely at them. We'll be exploring the following kinds of functions in Kotlin:

  • top-level functions
  • lambda expressions or function literals
  • anonymous functions
  • local or nested functions
  • infix functions
  • member functions

You'll be amazed at all the cool things you can do with functions in Kotlin!

1. Top-Level Functions

Top-level functions are functions inside a Kotlin package that are defined outside of any class, object, or interface. This means that they are functions you call directly, without the need to create any object or call any class. 

If you're a Java coder, you know that we typically create utility static methods inside helper classes. These helper classes don't really do anything—they don't have any state or instance methods, and they just act as a container for the static methods. A typical example is the Collections class in the java.util package and its static methods. 

Top-level functions in Kotlin can be used as a replacement for the static utility methods inside helper classes we code in Java. Let's look at how to define a top-level function in Kotlin. 

In the code above, we defined a package com.chikekotlin.projectx.utils inside a file called UserUtils.kt and also defined a top-level utility function called checkUserStatus() inside this same package and file. For brevity's sake, this very simple function returns the string "online". 

The next thing we'll do is to use this utility function in another package or file.

In the preceding code, we imported the function into another package and then executed it! As you can see, we don't have to create an object or reference a class to call this function.

Java Interoperability

Given that Java doesn't support top-level functions, the Kotlin compiler behind the scenes will create a Java class, and the individual top-level functions will be converted to static methods. In our own case, the Java class generated was UserUtilsKt with a static method checkUserStatus()

This means that Java callers can simply call the method by referencing its generated class, just like for any other static method.

Note that we can change the Java class name that the Kotlin compiler generates by using the @JvmName annotation.

In the code above, we applied the @JvmName annotation and specified a class name UserUtils for the generated file. Note also that this annotation is placed at the beginning of the Kotlin file, before the package definition. 

It can be referenced from Java like this:

2. Lambda Expressions

Lambda expressions (or function literals) are also not bound to any entity such as a class, object, or interface. They can be passed as arguments to other functions called higher-order functions (we'll discuss these more in the next post). A lambda expression represents just the block of a function, and using them reduces the noise in our code. 

If you're a Java coder, you know that Java 8 and above provides support for lambda expressions. To use lambda expressions in a project that supports earlier Java versions such as Java 7, 6, or 5, we can use the popular Retrolambda library

One of the awesome things about Kotlin is that lambda expressions are supported out of the box. Because lambda is not supported in Java 6 or 7, for Kotlin to interoperate with it, Kotlin creates a Java anonymous class behind the scene. But note that creating a lambda expression in Kotlin is quite different than it is in Java.

Here are the characteristics of a lambda expression in Kotlin:

  • It must be surrounded by curly braces {}.
  • It doesn't have the fun keyword. 
  • There is no access modifier (private, public or protected) because it doesn't belong to any class, object, or interface.
  • It has no function name. In other words, it's anonymous. 
  • No return type is specified because it will be inferred by the compiler.
  • Parameters are not surrounded by parentheses ()

And, what's more, we can assign a lambda expression to a variable and then execute it. 

Creating Lambda Expressions

Let's now see some examples of lambda expressions. In the code below, we created a lambda expression without any parameters and assigned it a variable message. We then executed the lambda expression by calling message()

Let's also see how to include parameters in a lambda expression. 

In the code above, we created a lambda expression with the parameter myString, along with the parameter type String. As you can see, in front of the parameter type, there is an arrow: this refers to the lambda body. In other words, this arrow separates the parameter list from the lambda body. To make it more concise, we can completely ignore the parameter type (already inferred by the compiler). 

To have multiple parameters, we just separate them with a comma. And remember, we don't wrap the parameter list in parentheses like in Java. 

However, note that if the parameter types can't be inferred, they must be specified explicitly (as in this example), otherwise the code won't compile.

Passing Lambdas to Functions

We can pass lambda expressions as parameters to functions: these are called "higher-order functions", because they are functions of functions. These kinds of functions can accept a lambda or an anonymous function as parameter: for example, the last() collection function. 

In the code below, we passed in a lambda expression to the last() function. (If you want a refresher on collections in Kotlin, visit the third tutorial in this series) As the name says, it returns the last element in the list.  last() accepts a lambda expression as a parameter, and this expression in turn takes one argument of type String. Its function body serves as a predicate to search within a subset of elements in the collection. That means that the lambda expression will decide which elements of the collection will be considered when looking for the last one.

Let's see how to make that last line of code above more readable.

The Kotlin compiler allows us to remove the function parentheses if the last argument in the function is a lambda expression. As you can observe in the code above, we were allowed to do this because the last and only argument passed to the last() function is a lambda expression. 

Furthermore, we can make it more concise by removing the parameter type.

We don't need to specify the parameter type explicitly, because the parameter type is always the same as the collection element type. In the code above, we're calling last on a list collection of String objects, so the Kotlin compiler is smart enough to know that the parameter will also be a String type. 

The it Argument Name

We can even simplify the lambda expression further again by replacing the lambda expression argument with the auto-generated default argument name it.

The it argument name was auto-generated because last can accept a lambda expression or an anonymous function (we'll get to that shortly) with only one argument, and its type can be inferred by the compiler.  

Local Return in Lambda Expressions

Let's start with an example. In the code below, we pass a lambda expression to the foreach() function invoked on the intList collection. This function will loop through the collection and execute the lambda on each element in the list. If any element is divisible by 2, it will stop and return from the lambda. 

Running the above code might not have given you the result you might have expected. This is because that return statement won't return from the lambda but instead from the containing function surroundingFunction()! This means that the last code statement in the surroundingFunction() won't execute. 

To fix this problem, we need to tell it explicitly which function to return from by using a label or name tag. 

In the updated code above, we specified the default tag @forEach immediately after the return keyword inside the lambda. We have now instructed the compiler to return from the lambda instead of the containing function surroundingFunction(). Now the last statement of surroundingFunction() will execute. 

Note that we can also define our own label or name tag. 

In the code above, we defined our custom label called myLabel@ and then specified it for the return keyword. The @forEach label generated by the compiler for the forEach function is no longer available because we have defined our own. 

However, you'll soon see how this local return problem can be solved without labels when we discuss anonymous functions in Kotlin shortly.

3. Member Functions

This kind of function is defined inside a class, object, or interface. Using member functions helps us to modularize our programs further. Let's now see how to create a member function.

This code snippet shows a class Circle (we'll discuss Kotlin classes in later posts) that has a member function calculateArea(). This function takes a parameter radius to calculate the area of a circle.

To invoke a member function, we use the name of the containing class or object instance with a dot, followed by the function name, passing any arguments if need be.

4. Anonymous Functions

An anonymous function is another way to define a block of code that can be passed to a function. It is not bound to any identifier. Here are the characteristics of an anonymous function in Kotlin:

  • has no name
  • is created with the fun keyword
  • contains a function body

Because we passed a lambda to the last() function above, we can't be explicit about the return type. To be explicit about the return type, we need to use an anonymous function instead.

In the above code, we have replaced the lambda expression with an anonymous function because we want to be explicit about the return type. 

Towards the end of the lambda section in this tutorial, we used a label to specify which function to return from. Using an anonymous function instead of a lambda inside the forEach() function solves this problem more simply. The return expression returns from the anonymous function and not from the surrounding one, which in our case is surroundingFunction().

5. Local or Nested Functions

To take program modularization further, Kotlin provides us with local functions—also known as nested functions. A local function is a function that is declared inside another function. 

As you can observe in the code snippet above, we have two single-line functions: calCircumference() and calArea() nested inside the printCircumferenceAndAread() function. The nested functions can be called only from within the enclosing function and not outside. Again, the use of nested functions makes our program more modular and tidy. 

We can make our local functions more concise by not explicitly passing parameters to them. This is possible because local functions have access to all parameters and variables of the enclosing function. Let's see that now in action:

As you can see, this updated code looks more readable and reduces the noise we had before. Though the enclosing function in this example given is small, in a larger enclosing function that can be broken down into smaller nested functions, this feature can really come in handy. 

6. Infix Functions

The infix notation allows us to easily call a one-argument member function or extension function. In addition to a function being one-argument, you must also define the function using the infix modifier. To create an infix function, two parameters are involved. The first parameter is the target object, while the second parameter is just a single parameter passed to the function. 

Creating an Infix Member Function

Let's look at how to create an infix function in a class. In the code example below, we created a Student class with a mutable kotlinScore instance field. We created an infix function by using the infix modifier before the fun keyword. As you can see below, we created an infix function addKotlinScore() that takes a score and adds to the kotlinScore instance field. 

Calling an Infix Function

Let's also see how to invoke the infix function we have created. To call an infix function in Kotlin, we don't need to use the dot notation, and we don't need to wrap the parameter with parentheses. 

In the code above, we called the infix function, the target object is student, and the double 95.00 is the parameter passed to the function. 

Using infix functions wisely can make our code more expressive and clearer than the normal style. This is greatly appreciated when writing unit tests in Kotlin (we'll discuss testing in Kotlin in a future post).

The to Infix Function

In Kotlin, we can make the creation of a Pair instance more succinct by using the to infix function instead of the Pair constructor. (Behind the scenes, to also creates a Pair instance.) Note that the to function is also an extension function (we'll discuss these more in the next post).

Let's now compare the creation of a Pair instance using both the to infix function and directly using the Pair constructor, which performs the same operation, and see which one is better.

As you can see in the code above, using the to infix function is more concise than directly using the Pair constructor to create a Pair instance. Remember that using the to infix function, 234 is the target object and the String "Nigeria" is the parameter passed to the function. Moreover, note that we can also do this to create a Pair type:

In the Ranges and Collections post, we created a map collection in Kotlin by giving it a list of pairs—the first value being the key, and the second the value. Let's also compare the creation of a map by using both the to infix function and the Pair constructor to create the individual pairs.

In the code above, we created a comma-separated list of Pair types using the to infix function and passed them to the mapOf() function. We can also create the same map by directly using the Pair constructor for each pair.

As you can see again, sticking with the to infix function has less noise than using the Pair constructor. 

Conclusion

In this tutorial, you learned about some of the cool things you can do with functions in Kotlin. We covered:

  • top-level functions
  • lambda expressions or function literals
  • member functions
  • anonymous functions
  • local or nested functions
  • infix functions

But that's not all! There is still more to learn about functions in Kotlin. So in the next post, you'll learn some advanced uses of functions, such as extension functions, higher-order functions, and closures. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts+!

  • Android SDK
    How to Use the Google Cloud Vision API in Android Apps
    Ashraff Hathibelagal
  • Java
    Android Design Patterns: The Observer Pattern
    Chike Mgbemena
  • Android SDK
    Adding Physics-Based Animations to Android Apps
    Ashraff Hathibelagal
  • Android SDK
    Android O: Phone Number Verification With SMS Tokens
    Chike Mgbemena
  • Android SDK
    What Are Android Instant Apps?
    Jessica Thornsby

by Chike Mgbemena via Envato Tuts+ Code

Make Your JavaScript Code Robust With Flow

JavaScript was always a significant programming language, being the only language that runs reliably in the browser. Recent trends in front-end development as well as Node.js based back-end development have pushed the scale and complexity of JavaScript applications. 

Large applications developed by large teams can benefit from static type checking, which vanilla JavaScript lacks. Flow was developed by Facebook to address this issue. It is a static type checker that integrates into your development process, catches a lot of problems early, and helps you move fast.

What Is Flow?

Flow is a tool that checks your annotated JavaScript code and detects various issues that without it would be discovered only at runtime (or worse, not discovered and corrupt your data). Here is a quick example.

Flow vs. TypeScript

Before diving into the nitty-gritty details of Flow, it's worthwhile to compare it against other alternatives, and in particular TypeScript. TypeScript is a strict superset of JavaScript developed by Microsoft. Any JavaScript program is also a TypeScript program. 

TypeScript adds optional type annotations and overall serves the same purpose as Flow. However, there are some important differences. TypeScript is a separate programming language that compiles to JavaScript, whereas Flow annotations must be removed to get back to valid JavaScript. 

TypeScript has great tool and IDE support. Flow is catching up (e.g. JetBrains WebStorm has native Flow integration).

The most important philosophical difference is that Flow puts an emphasis on soundness. TypeScript 1.0 didn't catch null errors; TypeScript 2.0 with strict null checks measured up to Flow in this regard. But in other aspects such as generic containers or typing, TypeScript is more permissive and lets various categories of errors through (only structural typing is checked, not nominal typing).

TypeScript as its own language adds concepts and language features such as classes, interfaces, visibility indicators (public, private, readonly), and decorators. Those features make it easier to understand and use for people coming from mainstream object-oriented languages like C++, Java, and C#.

Installation

Since Flow annotations are not standard JavaScript, they need to be removed before deploying your application. Here is how to install flow and flow-remove-types via yarn: yarn add --dev flow-bin flow-remove-types

You can add a couple of scripts to your package.json file to automate the process:

You should run the prepublish script before publishing your code to the npm registry.

For other installation options (e.g. using npm or babel), check out the Flow installation guide.

To finish the installation, type: yarn run flow init

This will create the required .flowconfig file.

Type System

Flow has two important goals: precision and speed. Its type system was designed to support these goals.

Precision

Precision is achieved by analyzing how the code interacts with types, either annotated or inferred. Any mismatch raises a type error. Annotated types support nominal typing, which means that two different types with the same attributes are distinguished from each other and can't be substituted. The type of a variable is defined as the set of runtime values the variable may receive. 

Speed

Flow is fast due to a combination of modularity and distributed processing. Files are analyzed in parallel, and the results are merged later via efficient shared memory to accomplish full-program type checking.

Supported Types

Flow supports many types. In addition to primitive types, it also supports the following:

  • Object
  • Array
  • Any
  • Maybe
  • Variable
  • Tuple
  • Class
  • Interface
  • Generic

Type Annotations

Flow allows you to declare types as well as restrict variables and parameters to selected values:

If you exceed the valid range, you'll get an error:

You can also define complex types, including subtyping. In the following code example, the Warrior type is a subtype of Person. This means it is OK to return a Warrior as a Person from the fight() function. However, returning null is forbidden.

To fix it, let's return the younger warrior if both warriors have the same strength:

Flow allows even more precise control via class extension, invariance, co-variance, and contra-variance. Check out the Flow documentation on variance.

Configuration

Flow uses the .flowconfig configuration file in the root directory of your projects. This file contains several sections that let you configure what files Flow should check and the many aspects of its operation. 

Include

The [include] section controls what directories and files should be checked. The root directory is always included by default. The paths in the [include] sections are relative. A single star is a wild-card for any filename, extension, or directory name. Two stars are a wild-card for any depth of directory. Here is a sample [include] section:

Ignore

The [ignore] section is the complement to [include]. Files and directories you specify here will not be checked by flow. Strangely, it uses a different syntax (OCaml regular expressions) and requires absolute paths. Changing this is on the roadmap of the Flow team.

Until then, remember that the include section is processed first, followed by the ignore section. If you include and ignore the same directory and/or file, it will be ignored. To address the absolute path issue, it is common to prefix every line with .*. If you want to ignore directories or files under the root, you can use the <PROJECT_ROOT> placeholder instead of .*. Here is a sample [ignore] section:

Libs

Any non-trivial JavaScript application uses lots of third-party libraries. Flow can check how your application is using these libraries if you provide special libdef files that contain type information about these libraries. 

Flow automatically scans the "flow-typed" sub-directory of your project for libdef files, but you may also provide the path of libdef files in the [libs] section. This is useful if you maintain a central repository of libdef files used by multiple projects.

Importing existing type definitions and creating your own if the target library doesn't provide its own type definitions is pretty simple. See:

Lints

Flow has several lint rules you can control and determine how to treat them. You can configure the rules from the command line, in code comments, or in the [lints] section of your config file. I'll discuss linting in the next section, but here is how to configure it using the [lints] section:

Options

The [options] section is where you get to tell Flow how to behave in a variety of cases that don't deserve their own section, so they are all grouped together.

There are too many options to list them all here. Some of the more interesting ones are:

  • all: set to true to check all files, not just those with @flow
  • emoji: set to true to add emojis to status messages
  • module.use_strict: set to true if you use a transpiler that adds "use strict;"
  • suppress_comment: a regex that defines a comment to suppress any flow errors on the following line (useful for in-progress code)

Check out all the options in the Flow guide to configuring options.

Version

Flow and its configuration file format evolve. The [version] section lets you specify which version of Flow the config file is designed for to avoid confusing errors.

If the version of Flow doesn't match the configured version, Flow will display an error message.

Here are a few ways to specify the supported versions:

The caret version keeps the first non-zero component of the version fixed. So ^1.2.3 expands to the range >=1.2.3 < 2.0.0, and ^0.4.5 expands to the range >= 0.4.5 < 0.5.0.

Using Flow From the Command Line

Flow is a client-server program. A Flow server must be running, and the client connects to it (or starts it if it's not running). The Flow CLI has many commands and options that are useful for maintenance and introspection purposes as well as for temporarily overriding configuration from .flowconfig.

Typing flow --help shows all the commands and options. To get help on a specific command, type flow <command> --help. For example:

Important commands are:

  • init: generate an empty .flowconfig file
  • check: do a full Flow check and print the results 
  • ls: display files visible to Flow
  • status (default): show current Flow errors from the Flow server
  • suggest: suggest types for the target file

Linting With Flow

Flow has a linting framework that can be configured via the .flowconfig file as you saw earlier, through command-line arguments, or in code files using flowlint comments. All configuration methods consist of a list of key-value pairs where the key is a rule and the value is the severity. 

Rules

There are currently three rules: all, untyped-type-import, and sketchy-null. The "All" rule is really the default handling for any errors that don't have a more specific rule. The "untyped-type-import" rule is invoked when you import a type from an untyped file. The "sketchy-null" rule is invoked when you do existence check on a value that can be false or null/undefined. There are more granular rules for:

  • sketchy-null-bool
  • sketchy-null-number
  • sketchy-null-string
  • sketchy-null-mixed

Severity Levels

There are also three severity levels: off, warning, and error. As you can imagine, "off" skips the type check, "warn" produces warnings, which don't cause the type check to exit and don't show up by default in the CLI output (you can see them with --include-warnings), and "error" is handled just like flow errors and causes the type check to exit and display an error message.

Linting With Command-Line Arguments

Use the --lints command-line argument to specify multiple lint rules. For example:

flow --lints "all=warn, untyped-type-import=error, sketchy-null-bool=off"

Linting With flowlint Comments

There are three types of comments: flowlint, flowlint-line, and flowlint-next-line.

The "flowlint" comment applies a set of rules in a block until overridden by a matching comment:

If there is no matching comment, the settings simply apply until the end of the file.

The "flowlint-line" applies just to the current line:  

The "flowlint-next-line" applies to the line following the comment:

Conclusion

Large JavaScript projects developed by large teams can benefit a lot from static type checking. There are several solutions for introducing static type checking into a JavaScript codebase. 

JavaScript continues to grow in a variety of ways across the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as you can see. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

Facebook's Flow is a recent and robust solution with excellent coverage, tooling, and documentation. Give it a try if you have a large JavaScript codebase.


by Gigi Sayfan via Envato Tuts+ Code