forked from optics-dev/Monocle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImportExample.scala
79 lines (54 loc) · 2.62 KB
/
ImportExample.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package other
import monocle.TestInstances
import org.scalatest.{Matchers, FunSuite}
import org.typelevel.discipline.scalatest.Discipline
import shapeless.test.illTyped
import shapeless.{::, HNil}
import scalaz.IList
case class Custom(value: Int)
object Custom {
import monocle.Lens
import monocle.function.Field1
implicit val customHead = new Field1[Custom, Int]{
def first = Lens((_: Custom).value)(v => c => c.copy(value = v))
}
}
// Cannot use MonocleSuite as it brings all imports
class ImportExample extends FunSuite with Discipline with Matchers with TestInstances {
test("monocle.function.all._ imports all polymorphic optics in the scope") {
import monocle.function.all._
// do not compile because Each instance for List is not in the scope
illTyped { """each[List[Int], Int].modify(List(1,2,3), _ + 1)""" }
import monocle.std.list._
each[List[Int], Int].modify(_ + 1)(List(1,2,3)) shouldEqual List(2,3,4)
// also compile because Head instance for Custom is in the companion of Custom
first[Custom, Int].modify(_ + 1)(Custom(1)) shouldEqual Custom(2)
}
test("monocle.syntax.all._ permits to use optics as operator which improves type inference") {
import monocle.function.all._
import monocle.std.list._
// do not compile because scala cannot infer which instance of Each is required
illTyped { """each.modify(List(1,2,3), _ + 1)""" }
each[List[Int], Int].modify(_ + 1)(List(1,2,3)) shouldEqual List(2,3,4)
}
test("monocle.std.all._ brings all polymorphic Optic instances in scope for standard Scala classes") {
import monocle.function.all._
import monocle.std.all._
// do not compile because Head instance for HList is not in scope
illTyped { """head[Int :: HNil, Int].modify(1 :: HNil, _ + 1) shouldEqual (2 :: HNil)""" }
each[List[Int], Int].modify(_ + 1)(List(1,2,3)) shouldEqual List(2,3,4)
each[IList[Int], Int].modify(_ + 1)(IList(1,2,3)) shouldEqual IList(2,3,4)
}
test("monocle.generic.all._ brings all polymorphic Optic instances in scope for Shapeless classes") {
import monocle.function.all._
import monocle.generic.all._
// do not compile because Each instance for List is not in scope
illTyped { """each[List[Int], Int].modify(List(1,2,3), _ + 1)""" }
first[Int :: HNil, Int].modify(_ + 1)(1 :: HNil) shouldEqual (2 :: HNil)
}
test("monocle._, Monocle._ makes all Monocle core features available (no generic)") {
import monocle._, Monocle._
each[List[Int], Int].modify(_ + 1)(List(1,2,3)) shouldEqual List(2,3,4)
each[IList[Int], Int].modify(_ + 1)(IList(1,2,3)) shouldEqual IList(2,3,4)
}
}