Skip to content

Commit

Permalink
Type-safe and readable contains checking (#43)
Browse files Browse the repository at this point in the history
* Type-safe and readable contains checking

* Type-safe and readable contains checking: tests

* Type-safe and readable contains checking: using value class
  • Loading branch information
akitaylor authored and lloydmeta committed Jul 12, 2016
1 parent b7f6dc3 commit da4a54d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
13 changes: 13 additions & 0 deletions enumeratum-core/src/main/scala/enumeratum/EnumEntry.scala
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,17 @@ object EnumEntry {
abstract override def entryName: String = super.entryName.toLowerCase
}

/**
* Helper implicit for more readable checking.
*/
implicit class ComparableEnum[A <: EnumEntry](val enum: A) extends AnyVal {
/**
* Checks if the current enum value is contained by the set of enum values in the parameter list.
* @param firstEnum First enum of the list.
* @param otherEnums Remaining enums.
* @return `true` if the current value is contained by the parameter list.
*/
def in(firstEnum: A, otherEnums: A*) = (firstEnum +: otherEnums).contains(enum)
}

}
23 changes: 22 additions & 1 deletion enumeratum-core/src/test/scala/enumeratum/EnumSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,28 @@ class EnumSpec extends FunSpec with Matchers {
case object Bar extends Foo
case object Baz extends Foo
}
""" shouldNot compile
""" shouldNot compile
}
}

describe("in") {
import DummyEnum._

it("should return true if enum value is contained by the parameter list") {
val enum: DummyEnum = Hello
enum.in(Hello, GoodBye) should be(true)
}

it("should return false if enum value is not contained by the parameter list") {
val enum: DummyEnum = Hi
enum.in(Hello, GoodBye) should be(false)
}

it("should fail to compile if either enum in the parameter list is not instance of the same enum type as the checked one") {
"""
val enum: DummyEnum = DummyEnum.Hi
enum.in(DummyEnum.Hello, SnakeEnum.ShoutGoodBye)
""" shouldNot compile
}
}

Expand Down

0 comments on commit da4a54d

Please sign in to comment.