This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Detect if AnyVal or AnyRef

2 replies
Naftoli Gugenheim
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
1.isInstanceOf[java.lang.Integer] == true
Same for pattern matching.
So how do you differentiate between a primitive value and its boxed equivalent?
Landei
Joined: 2008-12-18,
User offline. Last seen 45 weeks 4 days ago.
Re: Detect if AnyVal or AnyRef

Naftoli Gugenheim wrote:
>
> 1.isInstanceOf[java.lang.Integer] == true
> Same for pattern matching.
>
> So how do you differentiate between a primitive value and its boxed
> equivalent?
>
>

There is probably a better solution, but you can use the fact that implicit
conversion won't be "chained"

object test {

   case class IsVal(b:boolean)
  
   implicit def anyVal2isVal(i:AnyVal) = IsVal(true);
   implicit def anyRef2isVal(j:AnyRef) = IsVal(false);

   def testVal(t:IsVal) = t == IsVal(true);

   def main(args:Array[String]) {
      val i = 1
      val j = Integer.valueOf(2)
      println(testVal(i)) //-> true
      println(testVal(j))  //-> false
   }

}
Naftoli Gugenheim
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Detect if AnyVal or AnyRef
Not bad. Is there no better way, tough?

On Mon, Jan 12, 2009 at 7:47 AM, Landei <Daniel [dot] Gronau [at] gmx [dot] de> wrote:



Naftoli Gugenheim wrote:
>
> 1.isInstanceOf[java.lang.Integer] == true
> Same for pattern matching.
>
> So how do you differentiate between a primitive value and its boxed
> equivalent?
>
>

There is probably a better solution, but you can use the fact that implicit
conversion won't be "chained"
<pre>
object test {

  case class IsVal(b:boolean)

  implicit def anyVal2isVal(i:AnyVal) = IsVal(true);
  implicit def anyRef2isVal(j:AnyRef) = IsVal(false);

  def testVal(t:IsVal) = t == IsVal(true);

  def main(args:Array[String]) {
     val i = 1
     val j = Integer.valueOf(2)
     println(testVal(i)) //-> true
     println(testVal(j))  //-> false
  }

}
</pre>

--
View this message in context: http://www.nabble.com/Detect-if-AnyVal-or-AnyRef-tp21405484p21413739.html
Sent from the Scala - User mailing list archive at Nabble.com.


Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland