Scala REPL中类型别名和singleton对象之间的冲突

Scala REPL中类型别名和singleton对象之间的冲突,scala,Scala,我的代码为trait定义了一个类型别名,为该类型别名定义了一个单例对象。但是,在REPL中尝试使用这些时,我会遇到一些令人惊讶的错误 这是我能够重现问题的最少代码量。请注意,将所有内容拆分为不同的文件非常重要,将所有内容放在一起似乎可以解决问题 Decoder.scala package foo trait Decoder[E, D] { def decode(e: E): D } package object foo { type StringDecoder[A] = Decode

我的代码为trait定义了一个类型别名,为该类型别名定义了一个单例对象。但是,在REPL中尝试使用这些时,我会遇到一些令人惊讶的错误

这是我能够重现问题的最少代码量。请注意,将所有内容拆分为不同的文件非常重要,将所有内容放在一起似乎可以解决问题

Decoder.scala

package foo

trait Decoder[E, D] {
  def decode(e: E): D
}
package object foo {
  type StringDecoder[A] = Decoder[String, A]
}
package foo

object StringDecoder {
  def apply[A](f: String => A): StringDecoder[A] = new StringDecoder[A] { override def decode(s: String) = f(s) }

  def apply[A](implicit da: StringDecoder[A]): StringDecoder[A] = da

  def foobar: Unit = println("foobar")
}
package.scala

package foo

trait Decoder[E, D] {
  def decode(e: E): D
}
package object foo {
  type StringDecoder[A] = Decoder[String, A]
}
package foo

object StringDecoder {
  def apply[A](f: String => A): StringDecoder[A] = new StringDecoder[A] { override def decode(s: String) = f(s) }

  def apply[A](implicit da: StringDecoder[A]): StringDecoder[A] = da

  def foobar: Unit = println("foobar")
}
StringDecoder.scala

package foo

trait Decoder[E, D] {
  def decode(e: E): D
}
package object foo {
  type StringDecoder[A] = Decoder[String, A]
}
package foo

object StringDecoder {
  def apply[A](f: String => A): StringDecoder[A] = new StringDecoder[A] { override def decode(s: String) = f(s) }

  def apply[A](implicit da: StringDecoder[A]): StringDecoder[A] = da

  def foobar: Unit = println("foobar")
}
下面是一个示例REPL会话,展示了该问题:

scala> import foo._
import foo._

scala> implicit val test: StringDecoder[Float] = StringDecoder(_.toFloat)
test: foo.StringDecoder[Float] = foo.StringDecoder$$anon$1@40a4337a

scala> StringDecoder.foobar
<console>:15: error: value foobar is not a member of object foo.StringDecoder
       StringDecoder.foobar
我目前的解释是,当类型别名在类型别名之前引用类型别名时,对象以某种方式被类型别名遮挡,但我真的想不出为什么会发生这种情况。我也没有在REPL之外(或者在,本质上是REPL之外)重现这个问题


这种行为有什么已知的解释吗?

有什么已知的解释吗?不是真的,但这是一个已知的问题()

在对该问题的评论中,Jason Zaugg建议了一种解决方法,这意味着将您的
StringDecoder
更改为以下内容:

package foo

object StringDecoder0 {
  ...
}
然后:

package object foo {
  type StringDecoder[A] = Decoder[String, A]
  val StringDecoder: StringDecoder0.type = StringDecoder0
}
这不是正式的配对,但它支持预期用途(只要您没有在
StringDecoder0
中定义隐式实例)