Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

scala - Concrete classes with abstract type members

Given the following traits and class. Why does this compile? Can this be actually used for something?

trait Container {
  type A
}

trait AnotherContainer[B]{
    def x(b : B) : B
}

trait Mixed extends Container with AnotherContainer[Container#A]

class Impl extends Mixed{
    def x(a : Container#A) = a 
}

new Impl().x _

scala> new Impl().x _
res0: (Container#A) => Container#A = <function>

Update:

class Baz { type T; }

Is actually a feature but I could not find the motivation for it: #1753.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your example, the compiler adds the default type bounds of >: Nothing <: Any. The second example below shows a case where an abstract type becomes usable (if not useful).

scala> trait T { type A >: Nothing <: Any }
defined trait T

scala> 1: T#A
<console>:6: error: type mismatch;
 found   : Int(1)
 required: T#A
       1: T#A
       ^

scala> trait T { type A >: Int <: Int }
defined trait T

scala> 1: T#A                          
res6: T#A = 1

scala> "": T#A
<console>:6: error: type mismatch;
 found   : java.lang.String("")
 required: T#A
       "": T#A
       ^

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...