0
votes

I came across something like this recently

object example {
   type DButil = AnyRef {
     val a: Int
     def b: String
   }
}

Things that confused me is that usage of AnyRef here, later I dig a bit more, and I find you can also do this:

object apple {}
object example {
   type DButil = apple.type {
     val a: Int
     def b: String
   }
}

I've never seen this pattern before, any insights and comments are appreciated.

1
Is a structural type. Basically DButil is anything that has an a field of type Int, and a method b that receives nothing a returns a String; in the second example, such type also has to be a subclass of apple. Those are, IMHO, a bad feature; structural types relay in reflection (as such are insecure, slow, unsafe and less portable) and are not as flexible as they say they are. In my experience, they are used mostly by newcomers that come from languages like Python or JS and do not know how to properly model Polymorphism. - Luis Miguel Mejía Suárez
It's interesting that the 3rd edition of Programming In Scala dropped the 2nd edition's discussion of structural subtyping beyond refinement typing. - Levi Ramsey

1 Answers

0
votes

Type alias is just an additional name to the type. The constructions like AnyRef { val a: Int def b: String } apple.type { val a: Int def b: String } SomeSuperType { val structuralMember1: Int def structuralMember2: String }

is Anonymous Class/Type that inherits superclass behavior and contains additional structural type parts that defined in braces. And type alias is just a name for that Anonymous Type.