Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use scala trait with `self` reference?

Tags:

scala

I saw some code write trait as following:

trait SelfAware { self: Self =>  .... }  class Self val s = new Self with SelfAware // this is ok println(s.self) // error happened  class X new X with SelfAware // error happened here 

I'd like to know why the error happened and how to use trait in this way?

like image 401
Evans Y. Avatar asked Apr 24 '12 02:04

Evans Y.


People also ask

What is self => in Scala?

Self-types are a way to declare that a trait must be mixed into another trait, even though it doesn't directly extend it. That makes the members of the dependency available without imports. A self-type is a way to narrow the type of this or another identifier that aliases this .

What are traits and when can you use them in Scala?

Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait.

What is trait Scala?

A Trait is a concept pre-dominantly used in object-oriented programming, which can extend the functionality of a class using a set of methods. Traits are similar in spirit to interfaces in Java programming language. Unlike a class, Scala traits cannot be instantiated and have no arguments or parameters.

What is a mixin in Scala?

In scala, trait mixins means you can extend any number of traits with a class or abstract class. You can extend only traits or combination of traits and class or traits and abstract class. It is necessary to maintain order of mixins otherwise compiler throws an error.


1 Answers

The error is occurring because you have constrained the type of the this reference (which you have named self) to be of type Self. When you say new Self with SelfAware, this is OK, because that object is of type Self like you asked. But when you say new X with SelfAware, there is no evidence that X is in any way a subtype of Self.

In your new object of type X with SelfAware, what would be the type of its self member? Well, it would not be of type Self, but of type X. But you have defined the trait SelfAware so that self must be of type Self, so you get a type error.

like image 169
Apocalisp Avatar answered Sep 22 '22 19:09

Apocalisp