title: Advanced Type Constraints in Scala - Logical Operators and Implicit Parameters
body: <p>I have the following code which works well.</p>
  
  <pre><code>package com.andrew
  
  object ExperimentWithTypeConstraints {
  
    def union[T](t: T)(implicit c: (T =:= String)) = t match {
      case s: String =&gt; println(s"Some nice string: $s")
    }
  
    def main(args: Array[String]): Unit = {
      union("Hello.")
    }
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Some nice string: Hello.
  </code></pre>
  
  <p>I would like to modify the definition of the method <code>union</code> something like this:</p>
  
  <pre><code>   def union[T](t: T)(implicit c: (T =:= String) Or (T =:= Int)) = t match {
      case s: String =&gt; println(s"Some nice string: $s")
      case i: Int =&gt; println(s"Some int: $i")
    }
  </code></pre>
  
  <p>The output for <code>union(1)</code> should be the following one:  <code>Some int: 1</code></p>
  
  <p>Unfortunately, Scala does not know the logical operator Or (And, Not, ..) for such cases and hence it is not possible to compile it. How can I do it?</p>
  
  <p>I found one solution at the following address (<a href="http://hacking-scala.org/post/73854628325/advanced-type-constraints-with-type-classes" rel="nofollow noreferrer">http://hacking-scala.org/post/73854628325/advanced-type-constraints-with-type-classes</a>) but unfortunately I don't understand it well. Can you tell me how to solve this problem based on your approach? Or can you explain the solution from the above-mentioned url? Their solution works and it is the following:</p>
  
  <pre><code>@implicitNotFound("Argument does not satisfy constraints: ${A} Or ${B}")
  trait Or[A, B]
  
  object Or {
    private val evidence: Or[Any, Any] = new Object with Or[Any, Any]
  
    implicit def aExistsEv[A, B](implicit a: A) =
      evidence.asInstanceOf[Or[A, B]]
  
    implicit def bExistsEv[A, B](implicit b: B) =
      evidence.asInstanceOf[Or[A, B]]
  }
  </code></pre>
  
  <p>I don't understand the part with <code>Or</code>. <code>Or</code> is an object. How can I combine this part <code>(T =:= String) Or (T =:= Int)</code> via <code>Or</code> together?</p>
  
  <p>Thanks a lot, Andrew</p>