I would like to do something like this (example is simplified, but contains all the crucial pieces):
class Master
{
type DataType = Int
var counter : DataType = 0
}
class Slave(private val master : Master)
{
val counter = master.counter // (*)
}
And here (*) I get error:
private value master escapes its defining scope as part of type
Slave.this.master.DataTypeval counter = master.counter
I understand the error, but I don’t understand the reason – the type is part of the class Master, not the object master, so it is important if the class is private, not an object. Well, at least in theory.
It is easy to make a quick workaround:
val counter : Master#DataType = master.counter
But I believe this is an explicit version of the exactly same code as before, it “only” takes more typing. Is this a feature then?
QUESTION:
Can a type (here DataType) be dependent of the object, and not the class (i.e. type definition per instance of the class) in Scala?
You are wrong when you think
Master#DataTypeandmaster.DataTypeare two different types.master.DataTypeis the type of thoseDataTypeinstances which havemasteras outer object. In other words, precisely what you ask, but obviously thenmasteris part of the type, and the type can’t be exposed ifmasterisn’t.Master#DataTypeis the type of anyDataTypeinstance for any outer object (equivalent toMaster.DataTypein Java).REPLY TO THE COMMENT:
Type members can be overridden in a subclass (including an anonymous subclass containing only one object), but only by a compatible type. And in your example
DataTypeis already concrete inMaster, so the only compatible class with it is itself. So something likewon’t typecheck, which makes sense: you’d get
var counter: String = 0, which is nonsense. Butwill work (but isn’t too useful).
So it only ever makes sense to override abstract type members. But they are type-checked in the same way as inner classes, so
a.DataTypeis not generally considered the same asb.DataType— even if they can’t actually be different!