Scala: Traits implementation



In this blog we will learn how to implement traits in Scala
// trait is basically a kind of interface in scala which consists of definition of methods as well as unimplemented
// and partially implemented / implemented functions
trait exampletrait { // define trait with name exampletrait

val num=10; // variable of trait

def show(a:String):String // unimplemented method in traits
def sum(a1:Int,n:Int):Int= // implemented method in traits
return a1 + n


class traitclass extends exampletrait

def show(a:String):String=
return “hii “+ a

object mainobject
def main(args:Array[String])
var obj = new traitclass
println(“sum of integer 2 and 3 are ” + obj.sum(2, 2))
println(“access the variable of trait :” + obj.num)

// difference between traits and class
// trait :- we can not instantiate them , means cannot crate object of traits
// trait :- cannot create constructor of them


output will be like :-


hii scala
sum of integer 2 and 3 are 4
access the variable of trait :10



please like , share and comment



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s