Scala tag syntax

I am reading an Odersky book, and there is an example with a table with the following piece of code:

package org.stairwaybook.scells trait Arithmetic { this: Evaluator => operations += ( "add" -> { case List(x, y) => x + y }, "sub" -> { case List(x, y) => x - y }, "div" -> { case List(x, y) => x / y }, "mul" -> { case List(x, y) => x * y }, "mod" -> { case List(x, y) => x % y }, "sum" -> { xs => (0.0 /: xs)(_ + _) }, "prod" -> { xs => (1.0 /: xs)(_ * _) } ) } 

What does “this: appraiser” mean? Can someone help to understand this trait? As I see it, it defines different operations that are functions, but I do not see the big picture ...

+3
source share
1 answer

What do you see here

 this:Evaluator => 

- use of car for a sign. It basically forces the class that is going to mix the trait of arithmetic to also mix the sign of evaluation.

If you try to create a class, for example the following:

 class ArithmeticClass extends Arithmetic 

you get a compile-time error, and if you try to do:

 class ArithmeticClass extends Arithmetic with Evaluator 

it will work. As you can see, the Arithmetic class modifies adding something to the operations, which is probably a collection defined in the Evaluator attribute.

Note that the types themselves allow you to create a cleaner class hierarchy compared to simple inheritance:

If you use self types, you might think of something like the following:

 trait Evaluator { def runEvaluation : Int } trait Arithmetic { self: Evaluator => def evaluate: Int = runEvaluation } trait NullEvaluator extends Evaluator { def runEvaluation: Int = 0 } class MyClass1 extends Arithmetic with Evaluator {... concrete methods .... } class MyClass2 extends Arithmetic with NullEvaluator { ....concrete methods ..... } 

Thus, self types allow you to express something other than inheritance.

+10
source

All Articles