Scala Type Bounds: What is type bound?

Working with types in Scala can be challenging in many ways. The deeper you dig into the complexity of this subject, the more difficult is to find the right path. In this short post, I will be explaining some of the most fundamental of Scala type system — the type bounds. Enjoy!

What is type bound?

A type bound is nothing more than a mechanism to add restrictions to the type parameters. When passing a type to let’s say a class, we can limit to what types we want to allow. This mechanism allows for greater control over our code and hopefully making it more robust.

There are 3 distinct type bounds available in Scala — upper bound, lower bound and upper and lower combined. The chapters below explain how to use each of them.

Upper type bound

An upper type bound constraints a type A to be a subtype of B. The Scala notation looks like this:

class SomeClass[A <: B]

The example above defines the type of A as a subtype of B. To understand it better, let’s use some better example:

trait Eatable

class Vegetable extends Eatable
class Meat extends Eatable
class Potato extends Vegetable
class Beef extends Meat
class Orange extends Eatable
class Vegan[A <: Vegetable]
class Carnivore[A <: Meat]
class Food[A <: Eatable]
val vegan = new Vegan[Potato] // works fine
val mixed = new Carnivore[Potato] // error - type argument doesn't conform to type parameter bound
val all = new Food[Beef] // all good

As seen on a few examples above, the mechanism is pretty easy to use. The class Vegan, requires its type parameter to a subtype of Vegetable, which is exactly what Potato is. On the other hand, class Carnivore requires its parameter type to be a subtype of Meat, which Potato isn’t hence the error. The Food class accepts any class that extends Eatable trait - a Beef is one of them.

#scala #functional-programming #coding #programming #tutorial #function

What is GEEK

Buddha Community

Scala Type Bounds: What is type bound?
Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type

Myrl  Prosacco

Myrl Prosacco

1594453980

A Beginner's Guide to Scala 3.0

**Dotty, **a comprehensive name for all the things that are being added to Scala 3.0 has been a topic of discussion in the Scala community for the last four years. With all the promises and progress, The time for the release is very near. We can expect a release by the end of the year. In this post, we will get a teaser of what changes to expect from Dotty as well as some of the new changes in the major release. At the end of the post, we will see how we can quickly start with the Dotty compiler and example code.

Screenshot from 2020-06-04 08-41-20

What changes to expect from Dotty?

If you would ask, “Is Scala 3.0 a new language”, Martin Ordersky says “yes Or no” in “A tour of Dotty.” He has reasons for it. If you ask me, I would say yes!! It has a lot of new features.

  • If you are a beginner, and only starting with Scala 3, you will find the new features as a new concept that was not part of the old Scala.
  • Below snippet is a poll depicting the favorite changes for beginners in Scala 3.0. which was shared by Martin Ordersky in the last edition of ScalaDays.

Screenshot from 2020-06-04 08-48-09

  • However, it does not end here. There are more changes which you will see in the next section.
  • If you are at an intermediate level in scala and already familiar with the constructs of the language, you will see some of the features which are removed and no longer supported. We will see those in detail in the upcoming sections.
  • If you are a Scala expert and FP Enthusiast, there is a list of changes for you as well such as, **type-level derivation, match types, implicit function types, Metaprogramming **to name a few.
  • These changes are shared in “A tour of Dotty” by Martin Ordersky in the last edition of the ScalaDays.

Breaking Changes!

What do we mean by breaking changes? Those changes which are not going to be supported and compiling them in the newer version will require a re-write of the source in either a new way or to be removed. There are some features that are considered to have been pain points performance-wise or creating unnecessary complexity that is going to removed from Scala 3.0.

At a preview level here is the list of breaking changes:

**Macro:  **One of the biggest breaking change is Macros. The newer version of Scala includes a newer macros-system and Experimental Macro from Scala version 2.13 will not work in 3.0 and will have to be re-written.

**22-Arity: **The limits of 22 for the maximal number of parameters of function types and the maximal number of fields in tuple types have been dropped.

**And many more features. **Here is the list of all the breaking changes you should go through if you think you will be porting your code at some point in time.

An exhaustive list of Dropped Features is given below: 

#dotty #scala #scala days #beginners #dotty #functional programming in scala #scala 3

Scala Beginner Series (1) : Basics

This article will cover the fundamentals of Scala language.

Values

In Scala, we work with values:

Values are used to define constants. val modifier means constant or immutable that means we cannot change its value once it is created. Thus reassignment to val is prohibited.

It is evaluated at time of definition only. Once evaluated, it reuses same value for all references of it.

Variables

Scala also allows us to define mutable values. Variables are used to define mutable reference to a value. var modifier means changeable or mutable that means we can change its value throughout the program lifetime . Thus reassignment to var is allowed.

We do have the notion of a variable in Scala, but it’s heavily discouraged. In general, we work with immutable data structures: any intended modification to an existing instance should return a new (modified) instance.

Types

In Scala, we don’t always need to specify the data type of our value, because the compiler is smart enough to infer that for us. We can also write:

We can see, the compiler automatically inferred the data type of the value.

Strings

Strings in Scala are similar to what we see in other languages, but with some special functionalities:

String is defined as:

Whenever compiler encounters a string literal in the code, it creates a String object of java.lang.String class with its value.

Methods used to obtain information about an object are known as accessor methods.

One accessor method that can be used with strings is the length() method, which returns the number of characters contained in the string object.

The String class includes a method concat() for concatenating two strings. But strings are more commonly concatenated with the + operator.

String interpolation can also be done using string interpolator. It allows the direct usage of variable in processing a string, by injecting a value with the $ sign.

#scala #tech blogs #basics #scala #strings #types

Scala Type Bounds: What is type bound?

Working with types in Scala can be challenging in many ways. The deeper you dig into the complexity of this subject, the more difficult is to find the right path. In this short post, I will be explaining some of the most fundamental of Scala type system — the type bounds. Enjoy!

What is type bound?

A type bound is nothing more than a mechanism to add restrictions to the type parameters. When passing a type to let’s say a class, we can limit to what types we want to allow. This mechanism allows for greater control over our code and hopefully making it more robust.

There are 3 distinct type bounds available in Scala — upper bound, lower bound and upper and lower combined. The chapters below explain how to use each of them.

Upper type bound

An upper type bound constraints a type A to be a subtype of B. The Scala notation looks like this:

class SomeClass[A <: B]

The example above defines the type of A as a subtype of B. To understand it better, let’s use some better example:

trait Eatable

class Vegetable extends Eatable
class Meat extends Eatable
class Potato extends Vegetable
class Beef extends Meat
class Orange extends Eatable
class Vegan[A <: Vegetable]
class Carnivore[A <: Meat]
class Food[A <: Eatable]
val vegan = new Vegan[Potato] // works fine
val mixed = new Carnivore[Potato] // error - type argument doesn't conform to type parameter bound
val all = new Food[Beef] // all good

As seen on a few examples above, the mechanism is pretty easy to use. The class Vegan, requires its type parameter to a subtype of Vegetable, which is exactly what Potato is. On the other hand, class Carnivore requires its parameter type to be a subtype of Meat, which Potato isn’t hence the error. The Food class accepts any class that extends Eatable trait - a Beef is one of them.

#scala #functional-programming #coding #programming #tutorial #function

Myrl  Prosacco

Myrl Prosacco

1594483080

Dotty – Union Data Types

Hello folks, As we know that dotty is new Scala compiler (also know as Scala 3.0) which is coming with some new features and improvements. To get more details about the dotty and its environment setup. Please follow our beginner guide blog.

In this blog, I will describe you about newly introduced Union data type of dotty and its various properties.

A union is data type, which is denoted by “|” pipe infix operator and it looks like A | B. A union type (A | B) has a values of all values of type A and also all values of type B.

The primary reason for introducing union types in Scala is that they allow us to guarantee that for every set of types, we can always form a finite least upper bound (lub). This is both useful in practice as well as in theory. The type system of Scala 3 (i.e. dotty) is based on the DOT calculus, which has also a union data types.

A union type can also be joined with a non union types and form the finite join types. Like we can define join of a union type T1 | … | Tn as the smallest intersection type of base class instances of T1,…,Tn.

Syntactically, unions follow the same rules as intersections, but have a lower precedence than intersection(&).

Example of Dotty’s Union Types –

You can find the complete example of Dotty Union Type from here.

In this example, we have two case class models:

  • UserName
  • Password

Both have a common method lookup(). Which display the UserName and Password info on basis of its type calling.

We have also defined a getLoginInfo() method which takes a union type as an argument and return a union type value.

def getLoginInfo(loginInfo: UserName | Password): Password | UserName = {
    loginInfo match {
      case u@UserName(_) =>
        u.lookup
        u
      case p@Password(_) =>
        p.lookup
        p
    }
  }

Union types holds the commutative properties example: A | B =:= B | A

 val value1: UserName | Password = getLoginInfo(UserName("Narayan"))
  val value2: Password | UserName = getLoginInfo(UserName("Narayan"))
  if(value1 == value2) println("Commutative properties satisfy") else 
            println("Commutative properties does not satisfy")

Other Important points are –

  • Union type also supports distributive properties over the intersection (&) type.
  • Join operation on union types guarantees that the join is always finite.
  • The members of a union type are also the members of its join.
  • Union type “|” operator has lower precedence than both intersection(&) and type inference pattern (“:”) operators.
  • We can effectively use union type in pattern matching.

In next blog we will describe few more new data types of dotty. Like Type lambdas, Match types etc.

Stay Tunes, happy learning !!!

#dotty #scala #dotty #fintech #knoldus singapore #scala #singapore #singaporetech #union types