Scala: view app

Here is a short code:

import scala.language.implicitConversions implicit def str2int(str:String) = str.toInt object Container { def addIt[A](x: A)(implicit str2int: A => Int) = 123 + x def addIt2(x: String)(implicit str2int: String => Int) = 123 + x } println(Container.addIt("123")); println(Container.addIt2("123")); 

Two questions:

  • is "(implicit str2int: A => Int)" is called a view? When you say a “view” that indicates a particular piece of code?
  • Why does addIt return 246, while addIt2 returns the string "123123"?

A good resource on this topic would also be greatly appreciated. Thanks.

+6
source share
2 answers

The view means that type A can be “viewed” as type B , given by the implicit function A => B So yes, both implicit arguments in addIt and addIt2 are representations.

addIt2 returns 123123 , because (unfortunately) you can call + on two objects, where one of them is String . Before Scala considers applying the str2int transform. If you do not want this, you can explicitly apply the view:

 def addIt2(x: String)(implicit str2int: String => Int) = 123 + str2int(x) 

Or you can hide the any2stringadd conversion:

 object Container { import Predef.{any2stringadd => _} def addIt2(x: String)(implicit str2int: String => Int) = 123 + x } 
+4
source
  • Yes, this is an implicit representation, but it does not indicate any particular piece of code. He simply says that type A should be "convertible", preferably implicit, for type Int, for example. the implicit converter must be in scope when calling this method.

  • It looks like when the compiler translates the first method, it sees 123. + (x: A) and tries to find the implicit for type A that will compile '+'.

In the second case, however, he sees 123. + (x: String) and there is such an implicit conversion to Scala Predef. This is actually a fad in the implementation of Scala. Implicit declaration:

 final class StringAdd(self: Any) { def +(other: String) = self.toString + other } 

He stayed in Scala for the convenience of previous Java developers who used syntax like: 123 + "something" and expect it to be a string.

+2
source

Source: https://habr.com/ru/post/948520/


All Articles