具有两个通用参数的上下文范围 [英] Context bounds with two generic parameters

查看:86
本文介绍了具有两个通用参数的上下文范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,我可以使用上下文范围:

In Scala, I can use context bounds:

def sort[T : Ordered](t: Seq[T])

表示与以下内容相同的意思:

To mean the same thing as:

def sort[T](t: Seq[T])(implicit def Ordered[T])

如果我有一个带有两个通用参数的类,该怎么办? IE.我希望能够确保我有一个Writer[T, String].有没有可以使用上下文边界(T : ...)的语法,还是我需要显式地包含隐式的(写起来很有趣).

What if I have a class with two generic parameters. I.e. I want to be able to ensure that I have a Writer[T, String]. Is there a syntax where I can use context bounds (T : ...) or do I need to have the implicit explicitly (that was fun to write).

推荐答案

是的,有可能!但不是很漂亮:

Yes, it's possible! But not really very pretty:

trait Writer[T, O] {
  def write(t: T): O
}

def writeToString[T: ({ type L[x] = Writer[x, String] })#L](t: T) =
  implicitly[Writer[T, String]].write(t)

implicit object intToStringWriter extends Writer[Int, String] {
  def write(t: Int) = t.toString
}

然后:

scala> writeToString(1)
res0: String = 1

({ type L[x] = Writer[x, String] })#L称为 lambda类型.有时它们非常方便(如果

The ({ type L[x] = Writer[x, String] })#L thing is called a type lambda. Sometimes they're very convenient (if buggy), but this definitely isn't one of those times. You're much better off with the explicit implicit.

这篇关于具有两个通用参数的上下文范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆