简体   繁体   中英

Scala - Recursive view bounds

How do I get scala compiler to look for an implicit view recursively?

type Expression = () => String

implicit def constant(s: String): Expression = () => s

implicit def evaluation[A <% Expression](exprs: Seq[A]): Expression = () => exprs match {
  case "concat" :: args => args.map(_.apply()).mkString
}

Seq("concat", "foo", "bar")() // This works
Seq("concat", "foo", Seq("concat", "bar", "baz"))() // No implicit view available from java.lang.Object => () => String.

I understand that the last sequence has the common type Object which has no implicit view, but how can I define a type-safe one without resorting to dynamic pattern matching of AnyRef ?

Tried in scala 2.9.2

The type-inference figured out you have a Seq[Any] because of the mixed contents. The easiest solution is to help the compiler and tell it you have a Seq[Expression]

Seq[Expression]("concat", "foo", Seq("concat", "bar", "baz"))()

Edit

This is how you could solve it with tuples:

type Expression = () => String

implicit def constant(s: String): Expression = () => s

implicit def evaluation[A <% Expression, B <% Expression, C <% Expression](
  exprs: (A, B, C)): Expression = 
  () => exprs match {
    case ("concat", arg1, arg2) => arg1() + arg2()
  }

("concat", "foo", "bar")()                      //> res0: String = foobar
("concat", "foo", ("concat", "bar", "baz"))()   //> res1: String = foobarbaz

I also wondered why the scala compiler couldn't figure out that the inner Sequence was an expression - I figured, you simply forgot some brackets - here they are:

Seq("concat", "foo", Seq("concat", "bar", "baz")())() // added inner brackets

Edit

I see your point however - this also does not work:

val x: Expression = Seq("concat", "foo", "bar") // This works
val y: Expression = Seq("concat", "foo", x) // No implicit view available - again

so - here also it is necessary to provide the brackets for x.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM