Srinivas
Srinivas

Reputation: 2098

creating a new instance of a scala trait

Please explain this in Scala.

If I have a

 trait A

I cannot do a

val a = new A

But this example trait,

 trait DS[-In, +Out]{def apply(i: In): Out}

can have an instance of

val t1 = new DS[Any, Int]{def apply(i: Any) = i.toString.toInt}

How is this allowed?

Upvotes: 0

Views: 1387

Answers (2)

puhlen
puhlen

Reputation: 8529

What is happening is that by providing a class body you are creating an anonymous class inline that extends the trait.

Upvotes: 8

Reactormonk
Reactormonk

Reputation: 21740

Works just fine with a class body {}.

val a = new A {}

Upvotes: 5

Related Questions