Fail Compilation for Comparison of Different Types?

256 views
Skip to first unread message

Kevin Meredith

unread,
Aug 1, 2015, 8:15:01 PM8/1/15
to scala-user
Is there a scalac flag that will fail this compilation?

$scala "-Xfatal-warnings"


scala> val x: Seq[Option[Int]] = Seq( Some(1) )

x: Seq[Option[Int]] = List(Some(1))


// comparing Option[Int] to Int 

scala> x.map(_ == 4) 

res0: Seq[Boolean] = List(false)


Thanks,

Kevin

Dennis Haupt

unread,
Aug 2, 2015, 5:58:14 AM8/2/15
to Kevin Meredith, scala-user
you could use intellij (it has an inspection for this)
or you could define your own equals that only works on the same types using an implicit
 
Gesendet: Sonntag, 02. August 2015 um 02:15 Uhr
Von: "Kevin Meredith" <kevin.m....@gmail.com>
An: scala-user <scala...@googlegroups.com>
Betreff: [scala-user] Fail Compilation for Comparison of Different Types?
--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Oliver Ruebenacker

unread,
Aug 2, 2015, 8:23:01 AM8/2/15
to Dennis Haupt, Kevin Meredith, scala-user

     Hello,

  You can only proof that the comparison is never true if one of the types is final or sealed. It can be proven for the given example, because as it happens Int is final and Option is sealed. Below, Scala says "they will most likely never compare equal". Well, it didn't say "absolutely never".

[oruebenacker@localhost ~]$ scala
Welcome to Scala version 2.11.7 (OpenJDK 64-Bit Server VM, Java 1.8.0_51).
Type in expressions to have them evaluated.
Type :help for more information.

scala> trait A
defined trait A

scala> trait B
defined trait B

scala> class C extends A with B
defined class C

scala> val c = new C
c: C = C@57fa26b7

scala> val a: A = c
a: A = C@57fa26b7

scala> val b: B = c
b: B = C@57fa26b7

scala> a == b
<console>:17: warning: A and B are unrelated: they will most likely never compare equal
       a == b
         ^
res0: Boolean = true

     Best, Oliver

--
Oliver Ruebenacker
Senior Software Engineer, Diabetes Portal, Broad Institute

Reply all
Reply to author
Forward
0 new messages