Why my implicit function parameter does not work? - scala

Here is my code snippet:
implicit def trick(s: String): String = s.toUpperCase
def fun(s: String)(implicit f: String => String): String = f(s)
println(s"String is ${fun("abc")}")
When I run it, it prints "abc" instead of "ABC". What am I doing wrong here?
PS
However, if I run the next code
implicit val n: Int = 100
def add(n1: Int)(implicit n2: Int) = n1 + n2
add(7)
all implicit magic works just fine.

Normally this would work. The compiler would implicitly convert the implicit method to a function through eta-expansion. Say, if I wanted to require an implicit Int => List[Int] for some reason.
implicit def trick(i: Int): List[Int] = List.fill(5)(i)
def fun(i: Int)(implicit f: Int => List[Int]): List[Int] = f(i)
scala> fun(4)
res5: List[Int] = List(4, 4, 4, 4, 4)
But your problem is that there is another implicit String => String already in scope that comes from Predef. Namely =:=[String, String], which extends String => String. Because this already exists in scope as a function, the compiler sees no need to look for anything else. And, if you convert your implicit method to an implicit function, you will get an ambiguous implicits error:
implicit val trick: String => String = _.toUpperCase
scala> fun("abc")
<console>:19: error: ambiguous implicit values:
both method $conforms in object Predef of type [A]=> <:<[A,A]
and value trick of type => String => String
match expected type String => String
fun("abc")
Really though, having an implicit String => String is probably not a good idea. Use a type class that wraps a function, instead.
case class Trick[A](f: A => A)
implicit val trick = Trick[String](_.toUpperCase)
def fun(s: String)(implicit t: Trick[String]): String = t.f(s)
scala> println(s"String is ${fun("abc")}")
String is ABC

Related

Scala chaining implicits conversions for Option[T]

I try to make implicit conversions chain that from Symbol -> A -> Option[A]. But fail to make it working with generic Option conversion, for example:
implicit def toInt(n: Symbol): Int = n.toString.length
implicit def symbolToString(n: Symbol): String = n.toString
implicit def toOptStr[T](b: T)(implicit fn: T ⇒ String): Option[String] = Option(b)
implicit def toOptInt[T](b: T)(implicit fn: T ⇒ Int): Option[Int] = Option(b)
And it works fine:
val c: Option[Int] = 'a25768xffff // returns Some(12)
val d: Option[String] = 'a2699 // returns Some('a2699)
But I have to explicitly define toOptStr[T](b: T): Option[String] and toOptInt[T](b: T)(implicit fn: T ⇒ Int): Option[Int]
What I want to achieve instead is to have only one generic toOptT conversion, which can convert to Option[T] provided there is implicit conversion from T=>V, something like following:
implicit def toInt(n: Symbol): Int = n.toString.length
implicit def symbolToString(n: Symbol): String = n.toString
implicit def toOptT[T,V](b: T)(implicit fn: T ⇒ V): Option[V] = Option(fn(b))
val c: Option[Int] = 'a25768xffff
val d: Option[String] = 'a2699
Unfortunately, 2 last lines give compilation error:
Error:(34, 93) type mismatch;
found : Symbol
required: Option[Int]
Error:(35, 96) type mismatch;
found : Symbol
required: Option[String]
Any help is very much appreciated.
Tried it on Scala 12.2.5. There is somewhat related question: Chain implicit conversion of collection, chaining implicits details FAQ: https://docs.scala-lang.org/tutorials/FAQ/chaining-implicits.html
Couldn't make it work on 2.12.5.
Here is one possible workaround:
implicit val toInt: Symbol => Int = _.toString.length
implicit val symbolToString: Symbol => String = _.toString
implicit class ToOptOps[S](s: S) {
def toOpt[T](implicit c: S => T): Option[T] = Option(c(s))
}
val c = 'a25768xffff.toOpt[Int]
val d = 'a2699.toOpt[String]
I'd advice you to use only typeclasses in combination with implicit classes to "pimp-the-interface" (adding new methods, as toOpt in this case). Here, one should actually replace the implicit c: S => T by a proper typeclass, to avoid unwanted collisions. The combination of type classes with "pimping" has proven to be robust. In contrast to that, implicit conversions seem just evil.

default type conversions from sub to supertype, zero parameter functions

I am trying to understand the mechanism with which scala implements default type converions from sub to super type in scala.Predef. From the literature I gathered that this is done with the function
implicit def conforms[A] = new A<:<A { def apply(a:A)=a }
The parameterless function conforms[A] returns the implicit conversion A=>B as its only
function value (as a callable of type A=>A and thus of type A=>B, whenver A<:B).
However when the compiler looks for an implicit type conversion it needs an implicit value
of type A=>B not a function returning such a value. Thus my question:
When looking for a default type conversion from A=>B, where A<:B, how does the compiler
get from the function conforms[A] to its unique value.
The implicit resolution seeks for subtypes too, A <: B => A => A <: A => B, as in List[Int] <: Seq[Int].
scala> :paste
// Entering paste mode (ctrl-D to finish)
implicit val x: List[Int] = List(1, 2, 3)
def f(implicit x: Seq[Int]): Int = x.head
f
// Exiting paste mode, now interpreting.
x: Seq[Int] = List(1, 2, 3)
f: (implicit x: Seq[Int])Int
res1: Int = 1
So when making type conversion we look for A => B with A <: B, and A => A fits.
I'm not sure if I understood you right, but the defs are followed while searching for value of the needed type. It doesn't matter whether function takes zero, one, or more parameters. For example with zero:
implicit def implicitList[A]: List[A] = List() //the only obvious case
scala> implicitly[Seq[Int]]
// res0: Seq[Int] = List()
Or two:
case class Foo(str: String)
case class Bar(str: String)
case class Quux(str: String)
implicit val foo = Foo("foo")
implicit val bar = Bar("bar")
// how to build quux:
implicit def quux(implicit foo: Foo, bar: Bar): Quux = Quux(foo.str + bar.str)
implicitly[Quux]
// res2: Quux = Quux(foobar)
If we add any of:
implicit def quux2(implicit quux: Quux): Quux = quux
implicit def quux3(implicit foo: Foo): Quux = Quux(foo.str)
implicit val quux4: Quux = Quux("quux")
implicit def quux5[A]: Quux = Quux("poly")
We make implicit resolution undecidable for Quux:
scala> implicitly[Quux]
<console>:29: error: ambiguous implicit values:
both method quux of type (implicit foo: Foo, implicit bar: Bar)Quux
and method quux2 of type (implicit quux: Quux)Quux
match expected type Quux
implicitly[Quux]
^
I.e. there could be only one def or val in scope returning the type we are interested. And that is easy to verify statically.
But they will work if any of those is the only one in scope.

REPL could not find implicit

Hi I have an implicit method like:
implicit def strToOpt(str: String): Option[String] = Option(str)
and it works for simple conversion, but when I type
implicitly[String]
I get
error: could not find implicit value for parameter e: String
Does REPL have some limitations in term of finding implicits?
I think you have misunderstood implicitly. It is defined as:
def implicitly[T](implicit e: T): T = e
Which roughly means, that implicitly[T] will return you an object of type T which is available in current scope (scope is not the precise word. Compiler looks at many places)
In your case doing implicitly[String] simply means that some object of type String is available.
For example this is valid:
scala> implicit val x = "Hey"
x: String = Hey
scala> implicitly[String]
res12: String = Hey
But what you rather need to do is:
scala> implicitly[(String) => Option[String]]
res10: String => Option[String] = <function1>
scala> res10("asd")
res11: Option[String] = Some(456)
PS: Note answer by #Ende Neu works as:
implicitly[Option[String]]("123")
Doing implicitly[Option[String]]("123"), in the implicitly function it takes T as argument which is String. But you have manually provided Option[String] as type parameter of method. So the compiler searches for a function again (by using implicitly again) that does String => Option[String] which it finds in your function.

Why implicit conversion doesn't work in Lists?

Could someone give a quick explanation why implicit conversion doesn't work in these cases? Thanks.
scala> implicit def strTwoInt (s: String):Int = s.toCharArray.map{_.asDigit}.sum
strTwoInt: (s: String)Int
scala> List[Int]("1","2","3") sum
res3: Int = 6
scala> List("1","2","3") sum
<console>:9: error: could not find implicit value for parameter num: Numeric[java.lang.String]
List("1","2","3") sum
scala> val a = List("1","2","3")
scala> a.foldLeft(0)((i:Int, j:Int) => i+j)
<console>:10: error: type mismatch;
found : (Int, Int) => Int
required: (Int, java.lang.String) => Int
Your implicit conversion converts a String in an Int. In your first example, it is triggered by the fact that you try to put Strings into a List of Ints.
In your second example, you have a List of String and you call the method sum, which takes an implicit Numeric[String]. Your conversion does not apply because you neither try to pass a String somewhere the compiler was expecting an Int, nor you tried to call a method which is defined in Int and not in String. In that case, you can either define a Numeric[String] which use explicitly your conversion, or use a method which takes a List[Int] as parameter (giving hint to the compiler):
scala> def sumIt( xs: List[Int] ) = xs sum
sumIt: (xs: List[Int])Int
scala> sumIt( List("1","2","3") )
res5: Int = 6
In the third example, the foldLeft second argument must be of type:
(Int,String) => Int
the one you actually passed is of type:
(Int,Int) => Int
however, you did not define any implicit conversion between these two types. But:
a.foldLeft(0)((i:Int, j:String) => i+j)
triggers your conversion and works.
Edit: Here's how to implement the Numeric[String]:
implicit object StringNumeric extends math.Numeric[String] {
val num = math.Numeric.IntIsIntegral
def plus(x: String, y: String) = num.plus(x,y).toString
def minus(x: String, y: String) = num.minus(x,y).toString
def times(x: String, y: String) = num.times(x,y).toString
def negate(x: String): String = num.negate(x).toString
def fromInt(x: Int) = x.toString
def toInt(x: String) = x
def toLong(x: String) = toInt(x)
def toFloat(x: String) = toInt(x)
def toDouble(x: String) = toInt(x)
def compare(x:String,y:String) = num.compare(x,y)
}
scala> List("1","2","3") sum
res1: java.lang.String = 6
It works, but the result is a String.
Here's a quick explanation: implicit conversions apply to the types the convert from and to directly (e.g., String and Int in your case), and not to any parametrized type T[String] or T[Int] — unless implicit conversions have been defined for T itself, and it is not the case for lists.
Your implicit conversion does not apply in your two cases (and even if you had an implicit conversion from List[String] to List[Int], it wouldn't apply). It would automatically applied only when you need a value of type Int and you're passing String instead. Here, in the first case, the method sum asks for a Numeric[String] implicit parameter — an implicit conversion from String to Int does not come into play here.
Similar problem for your next attempt: the foldLeft on your collection requires a function of type (Int, String) => Int. Imagine the mess we would get into if, based on an implicit conversion from String to Int, the compiler automatically provided an implicit conversion from (Int, Int) => Int to (Int, String) => Int…
For all these cases, the easy way to fix it is to explicitly call .map(stringToInt) on your collection beforehand.

What is the Scala identifier "implicitly"?

I have seen a function named implicitly used in Scala examples. What is it, and how is it used?
Example here:
scala> sealed trait Foo[T] { def apply(list : List[T]) : Unit }; object Foo {
| implicit def stringImpl = new Foo[String] {
| def apply(list : List[String]) = println("String")
| }
| implicit def intImpl = new Foo[Int] {
| def apply(list : List[Int]) = println("Int")
| }
| } ; def foo[A : Foo](x : List[A]) = implicitly[Foo[A]].apply(x)
defined trait Foo
defined module Foo
foo: [A](x: List[A])(implicit evidence$1: Foo[A])Unit
scala> foo(1)
<console>:8: error: type mismatch;
found : Int(1)
required: List[?]
foo(1)
^
scala> foo(List(1,2,3))
Int
scala> foo(List("a","b","c"))
String
scala> foo(List(1.0))
<console>:8: error: could not find implicit value for evidence parameter of type
Foo[Double]
foo(List(1.0))
^
Note that we have to write implicitly[Foo[A]].apply(x) since the compiler thinks that implicitly[Foo[A]](x) means that we call implicitly with parameters.
Also see How to investigate objects/types/etc. from Scala REPL? and Where does Scala look for implicits?
implicitly is avaliable in Scala 2.8 and is defined in Predef as:
def implicitly[T](implicit e: T): T = e
It is commonly used to check if an implicit value of type T is available and return it if such is the case.
Simple example from retronym's presentation:
scala> implicit val a = "test" // define an implicit value of type String
a: java.lang.String = test
scala> val b = implicitly[String] // search for an implicit value of type String and assign it to b
b: String = test
scala> val c = implicitly[Int] // search for an implicit value of type Int and assign it to c
<console>:6: error: could not find implicit value for parameter e: Int
val c = implicitly[Int]
^
Here are a few reasons to use the delightfully simple method implicitly.
To understand/troubleshoot Implicit Views
An Implicit View can be triggered when the prefix of a selection (consider for example, the.prefix.selection(args) does not contain a member selection that is applicable to args (even after trying to convert args with Implicit Views). In this case, the compiler looks for implicit members, locally defined in the current or enclosing scopes, inherited, or imported, that are either Functions from the type of that the.prefix to a type with selection defined, or equivalent implicit methods.
scala> 1.min(2) // Int doesn't have min defined, where did that come from?
res21: Int = 1
scala> implicitly[Int => { def min(i: Int): Any }]
res22: (Int) => AnyRef{def min(i: Int): Any} = <function1>
scala> res22(1) //
res23: AnyRef{def min(i: Int): Int} = 1
scala> .getClass
res24: java.lang.Class[_] = class scala.runtime.RichInt
Implicit Views can also be triggered when an expression does not conform to the Expected Type, as below:
scala> 1: scala.runtime.RichInt
res25: scala.runtime.RichInt = 1
Here the compiler looks for this function:
scala> implicitly[Int => scala.runtime.RichInt]
res26: (Int) => scala.runtime.RichInt = <function1>
Accessing an Implicit Parameter Introduced by a Context Bound
Implicit parameters are arguably a more important feature of Scala than Implicit Views. They support the type class pattern. The standard library uses this in a few places -- see scala.Ordering and how it is used in SeqLike#sorted. Implicit Parameters are also used to pass Array manifests, and CanBuildFrom instances.
Scala 2.8 allows a shorthand syntax for implicit parameters, called Context Bounds. Briefly, a method with a type parameter A that requires an implicit parameter of type M[A]:
def foo[A](implicit ma: M[A])
can be rewritten as:
def foo[A: M]
But what's the point of passing the implicit parameter but not naming it? How can this be useful when implementing the method foo?
Often, the implicit parameter need not be referred to directly, it will be tunneled through as an implicit argument to another method that is called. If it is needed, you can still retain the terse method signature with the Context Bound, and call implicitly to materialize the value:
def foo[A: M] = {
val ma = implicitly[M[A]]
}
Passing a subset of implicit parameters explicitly
Suppose you are calling a method that pretty prints a person, using a type class based approach:
trait Show[T] { def show(t: T): String }
object Show {
implicit def IntShow: Show[Int] = new Show[Int] { def show(i: Int) = i.toString }
implicit def StringShow: Show[String] = new Show[String] { def show(s: String) = s }
def ShoutyStringShow: Show[String] = new Show[String] { def show(s: String) = s.toUpperCase }
}
case class Person(name: String, age: Int)
object Person {
implicit def PersonShow(implicit si: Show[Int], ss: Show[String]): Show[Person] = new Show[Person] {
def show(p: Person) = "Person(name=" + ss.show(p.name) + ", age=" + si.show(p.age) + ")"
}
}
val p = Person("bob", 25)
implicitly[Show[Person]].show(p)
What if we want to change the way that the name is output? We can explicitly call PersonShow, explicitly pass an alternative Show[String], but we want the compiler to pass the Show[Int].
Person.PersonShow(si = implicitly, ss = Show.ShoutyStringShow).show(p)
Starting Scala 3 implicitly has been replaced with improved summon which has the advantage of being able to return a more precise type than asked for
The summon method corresponds to implicitly in Scala 2. It is
precisely the same as the the method in Shapeless. The difference
between summon (or the) and implicitly is that summon can return a
more precise type than the type that was asked for.
For example given the following type
trait F[In]:
type Out
def f(v: Int): Out
given F[Int] with
type Out = String
def f(v: Int): String = v.toString
implicitly method would summon a term with erased type member Out
scala> implicitly[F[Int]]
val res5: F[Int] = given_F_Int$#7d0e5fbb
scala> implicitly[res5.Out =:= String]
1 |implicitly[res5.Out =:= String]
| ^
| Cannot prove that res5.Out =:= String.
scala> val x: res5.Out = ""
1 |val x: res5.Out = ""
| ^^
| Found: ("" : String)
| Required: res5.Out
In order to recover the type member we would have to refer to it explicitly which defeats the purpose of having the type member instead of type parameter
scala> implicitly[F[Int] { type Out = String }]
val res6: F[Int]{Out = String} = given_F_Int$#7d0e5fbb
scala> implicitly[res6.Out =:= String]
val res7: res6.Out =:= String = generalized constraint
However summon defined as
def summon[T](using inline x: T): x.type = x
does not suffer from this problem
scala> summon[F[Int]]
val res8: given_F_Int.type = given_F_Int$#7d0e5fbb
scala> summon[res8.Out =:= String]
val res9: String =:= String = generalized constraint
scala> val x: res8.Out = ""
val x: res8.Out = ""
where we see type member type Out = String did not get erased even though we only asked for F[Int] and not F[Int] { type Out = String }. This can prove particularly relevant when chaining dependently typed functions:
The type summoned by implicitly has no Out type member. For this
reason, we should avoid implicitly when working with dependently typed
functions.
A "teach you to fish" answer is to use the alphabetic member index currently available in the Scaladoc nightlies. The letters (and the #, for non-alphabetic names) at the top of the package / class pane are links to the index for member names beginning with that letter (across all classes). If you choose I, e.g., you'll find the implicitly entry with one occurrence, in Predef, which you can visit from the link there.