Expects a String?

11 views
Skip to first unread message

Lyle Kopnicky

unread,
Mar 16, 2015, 2:10:32 AM3/16/15
to pdxs...@googlegroups.com

Hi folks,

What the heck is going on here? Why does this expect a string?

scala> def double[A: Numeric](a: A) = a + a
<console>:7: error: type mismatch;
 found   : A
 required: String
       def double[A: Numeric](a: A) = a + a
                                          ^

Thanks,
Lyle

Robert Norris

unread,
Mar 16, 2015, 2:14:59 AM3/16/15
to pdxs...@googlegroups.com

Yeah, you're getting the + from Predef.any2stringadd which is awful ... it basically lets you add a String to anything at all and get a String back. What you want is the + from Numeric.Ops which you can get by importing Numeric.Implicits._ thus:

scala> def double[A: Numeric](a: A) = a + a
<console>:7: error: type mismatch;
found : A
required: String
def double[A: Numeric](a: A) = a + a
^

scala> import Numeric.Implicits._
import Numeric.Implicits._

scala> def double[A: Numeric](a: A) = a + a
double: [A](a: A)(implicit evidence$1: Numeric[A])A

scala> double(1)
res0: Int = 2

scala> double(1.2)
res1: Double = 2.4
> --
> You received this message because you are subscribed to the Google Groups "pdxscala" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to pdxscala+u...@googlegroups.com.
> To post to this group, send email to pdxs...@googlegroups.com.
> Visit this group at http://groups.google.com/group/pdxscala.
> For more options, visit https://groups.google.com/d/optout.

Lyle Kopnicky

unread,
Mar 16, 2015, 2:27:28 AM3/16/15
to pdxs...@googlegroups.com

Thanks, Rob!

Yeah, I don’t see the use in Predef.any2stringadd when you have string interpolation, and the format method on Strings.

I’m surprised that Numeric would be included by default, but not the implicits. But then again, I guess it’s safer not to include the implicits.

If only that safety rule were followed with any2stringadd.

So much simpler in Haskell:

Prelude> let double n = n + n
Prelude> double 1
2
Prelude> double 1.2
2.4
Reply all
Reply to author
Forward
0 new messages