Scala view application puzzler

前端 未结 5 1726
粉色の甜心
粉色の甜心 2021-02-04 09:20

Say we have the following two traits:

trait Foo[A] { def howMany(xs: List[A]) = xs.size }
trait Bar

And an implicit conversion from the second

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-04 09:59

    Your implicit conversion seems to be doing exactly what you told it to do.

    implicit def bar2foo[A](bar: Bar) = new Foo[A] {}
    

    Converts a Bar to a new Foo[A] object. So in turn

    scala> bar howMany stuff
    :13: error: type mismatch;
     found   : List[Int]
     required: List[A]
                  bar howMany stuff
    

    It looks for an 'A' type.

    In order to make this work the way you want it to you (I think), instead of defining the view on the trait you can do it on the function.

    trait Foo { def howMany[A](xs: List[A]) = xs.size }
    trait Bar
    implicit def bar2foo[A](bar: Bar) = new Foo{}
    val bar = new Bar {}
    val stuff = List(1, 2, 3)
    

    then it should give you the result you desire.

    scala> bar howMany stuff
    res0: Int = 3
    

    or you can define the view on the implicit function

    trait Foo[A] { def howMany(xs: List[A]) = xs.size }
    trait Bar
    
    implicit def bar2foo[A](bar: Bar) = new Foo[Int] {}
    
    val bar = new Bar {}
    val stuff = List(1, 2, 3)
    

    Personally I think defining it on the function is cleaner.

提交回复
热议问题