Scala Programming - Traits, reusing the code

in #utopian-io7 years ago (edited)



What Will I Learn?

  • Advanced programming in the Scala programming language, with easy explanation.
  • Traits - it's something between the interface and the class.

Requirements

  • Knowledge of medium-level programming
  • Impeccable intelligence in the meaning of IT phrases
  • Downloaded Java version 1.5 and above
  • For windows it is recommended to download the "IZPACK Installer" package, which automatically installs environment variables.

Difficulty

  • Intermediate, but for some people it can be Advanced.

Tutorial Contents



Traits, it's like I wrote before, something between the interface and the class.

Once a professor told us the two most important sentences about Traits.


Traits is the basic unit for reusing code in Scala. In order to increase the efficiency and quality of programs, various abstractions are used to facilitate re-use of the code.



This is a definition that is worth assimilating to understand the basic principle of Traits.



They contain abstract and specific fields and methods

• Encapsulate and facilitate reuse

• They allow to extend the interfaces in a convenient way

• They allow modifications to the existing methods

• They can be repeatedly mixed (mixin) to classes thus provide multi-inheritance




As we all know, the best method of learning is practice. Therefore, immediately omitting the theory given by me, let's move to practice. We will start by showing the operation of Traits on examples.

Operation of traits on examples:

TRAITS

abstract class Utopians
trait HasSteem {
val steem: List[String]
def walk = println("walking")
}
trait CollectCrypto {
def collectCrypto: Unit
}
class Frog(val name: String) extends Utopians with HasSteem with CollectCrypto {
override val steem = List("one", "two")
override def collectCrypto = println("strum")
}

Defining the abstract class Utopians
The definition of trait is based on giving the key word "trait". The remaining definition looks like an abstract class. We can define both abstract and specific methods and fields. In the example I defined an abstract "steem" field, which is of the "list string" type.

The "steem" field must be initialized in a specific "HasSteem" expansion class. Otherwise, the compiler will report an error:

scala> class "XXX" extends HasSteem
<console>:8: error: class "XXX" needs to be abstract, since value steem in trait HasSteem of type List[String] is not defined
class "XXX" extends HasSteem



After implementing the abstract field, we can use the functions defined in HasSteem:

scala> val username = new User
username: User = User@254865c6
scala> username.walk
walking



Let's define now, a small abstraction modeling Cars. The base class will be Car, and we will create two Traits: HasWheels and AreLoud.

abstract class Car
trait HasWheels {
val wheels: List[String]
def drive = println("driving")
}
trait AreLoud {
def areLoud: Unit
}

An example of the implementation of a Sport Car (for eg.) BMW:

class BMW(val name: String) extends Car with HasWheels with AreLoud {
val wheels = List("one", "two")
def areLoud = println("wrrrum wrrrum")
}

By using the keyword "with" we mix another Traits into the class. If there is a name conflict, the compiler will ask you to provide your own implementation by overwriting this one with Traits.

trait CanRun {
def run = println("I can run")
}

now the next part of the code:

class Car extends HasWheels with CanRun {
val wheels = List("wheel 1", "wheel 2", "wheel 3", "wheel 4")
}
<console>:26: error: overriding method walk in trait HasWheels of type => Unit;
method run in trait CanRun of type => Unit needs `override' modifier
class Car extends HasWheels with CanRun {

After overwriting the conflicting method, the Dog class compiles without error.

class Car extends HasWheels with CanRun {
val wheels = List("wheel 1", "wheel 2", "wheel 3", "wheel 4")
override def run = println("Noise!")
}

Let's see an example of the class Utopians, which inherits only after CollectCrypto:

class Utopians extends CollectCrypto {
def CollectCrypto = println("money!")
}

Unlike Java, we are not limited to one line of inheritance, which results in shallower hierarchies. Idiomatic code is very often used by mixing traits.


In addition to multi-inheritance, Traits allow you to create so-called stack modifications.


How they work, it's best to see the example. Below the queue example, and a specific implementation for type Int, for simplicity, the queue has one function: adding and a list for storing elements.

trait Queue[T] {
def adding(x: T): Unit
}

Stacking modifications are marked with the abstract override keyword. This combination is only allowed in Traits.

trait Adder extends IntQueue {
abstract override def adding(x: Int) = super.adding(x + 1)
}
trait Twicer extends IntQueue {
abstract override def adding(x: Int) = super.adding(x * 2)
}
trait IntQueue extends Queue[Int]
class BasicIntQueue(var elems: List[Int]) extends IntQueue {
override def adding(x: Int) = elems = x :: elems
}

The use of abstract override allows you to call the code before or after the function that you overwrite. If you want to change the operation of the queue, just (mixin) the appropriate Traits.



If you have any problems with Traits, please write to me on the discord, on the utopian server under the same username as on the utopian.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules/Guidelines.

Violated Rule(s)/Guideline(s):

  • Submissions containing substantial instruction in ubiquitous functions (Save, Open, Print, etc.) or basic programming concepts (variables, operators, loops, etc.) will be rejected.

My Opinion(s):

  • As it's stated in the rule which I marked above, this tutorial contains basic programming concepts.

Need help? Write a ticket on https://support.utopian.io.

Chat with us on Discord.

[utopian-moderator]

Congratulations @mubek! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes received

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Upvote this notification to help all Steemit users. Learn why here!

Congratulations @mubek! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.25
TRX 0.20
JST 0.038
BTC 94956.90
ETH 3542.14
USDT 1.00
SBD 3.80