Scala Typeclasses

aba*_*rek 3 functional-programming scala typeclass

我正在尝试实现简单类型类模式.它假设与scalaz的类型类似.不幸的是我无法让它发挥作用.我有特质Str

trait Str[T] {
  def str(t: T): String
}

object Str {
  def apply[T](implicit instance: Str[T]) : Str[T] = instance
}
Run Code Online (Sandbox Code Playgroud)

在我和它的隐含实例中.

object Temp extends App {

  implicit val intStr = new Str[Int] {
    def str(i: Int) = i.toString
  }

  1.str //error: value str is not a member of Int

}
Run Code Online (Sandbox Code Playgroud)

我很感激任何见解.

Łuk*_*asz 8

你现在可以做的一切都是

Str[Int].str(1)
Run Code Online (Sandbox Code Playgroud)

使用1.str你需要引入隐式转换.

例如,您可以使用此方法:

implicit class StrOps[A](val self: A) extends AnyVal {
    def str(implicit S: Str[A]) = S.str(self)
}
Run Code Online (Sandbox Code Playgroud)

这使:

scala> 1.str
res2: String = 1
Run Code Online (Sandbox Code Playgroud)