开发者

Why aren't self-types looked up when calling a method on a constrained trait?

开发者 https://www.devze.com 2023-02-19 07:15 出处:网络
Assuming trait A { def t : Int } trait B { this: A => } why is it that the compiler doesn\'t \"know\" that I can call t on B?

Assuming

trait A { def t : Int }
trait B { this: A => }

why is it that the compiler doesn't "know" that I can call t on B?

def test(b: B): Int = b.t // doesn't work

but that I (apparently redundantly?) need to do

def test(b: B with A): Int 开发者_运维百科= b.t


Self-types are not part of the contract of a trait or class. That is to say, they don't provide externally visible restrictions on a trait or class, only internally visible ones. Self-types are checked at object instantiation time, but are otherwise only usable by the declaring trait or any inheriting traits/classes/objects. In Java terms, you could think of a self-type as being something like a a protected interface declared by the trait (although Java of course doesn't actually support such a thing).

If you wanted your test to work, you would need to make the dependence of B on A externally visible. This is done with an "extends" declaration, a.k.a. simple subclassing

trait A { def t : Int }
trait B extends A
def test( b: B ) : Int = b.t
0

精彩评论

暂无评论...
验证码 换一张
取 消