Transfer Function in Scala

Since Java 8 I can go from

xyz.foreach(e -> System.out.println(e));

I can do the following

xyz.foreach(System.out::println)

I saw this thread about how method references work, but the problem is this:

Error: (16, 63) ambiguous reference to overloaded definition,

both toJson methods in an IanesJsonHelper object of type (source: IanesServer) String

and the toJson method in an IanesJsonHelper object of type (success: Boolean) String

corresponds to the expected type Function [?, String]

 val json = IanesJsonHelper.toJson(array,IanesJsonHelper.toJson _)

                                                        ^

I have 3 functions named "toJSON"

def toJson(id: Int): String

and

 def toJson(success: Boolean): String

and

 def toJson(source: IanesServer): String

The last one is correct.

The function that I called in the error message above:

def toJson[T](source: Array[T], toJson: Function[T, String]): String

This is the corresponding code:

 val array = new Array[IanesServer](1)
 array(0) = new IanesServer(1, "http://localhost:4567/", "Test")
 val json = IanesJsonHelper.toJson(array,IanesJsonHelper.toJson)

I do not understand what my error is:

  • The array is of type IanesServer
  • T in the calling method should be IanesServer (Array [IanesServer] → Array [T]
  • - 2. T , T , Function [IanesServer, String] → [T, String]

-, , , ? , [?, String]. ?

: , :

 IanesJsonHelper.toJson[IanesServer](array,IanesJsonHelper.toJson)
+4
1
def toJson[T](source: Array[T], toJson: Function[T, String]): String

, toJson Function[IanesServer, String], source Array[IanerServer] - T IanesServer.

, scala . :

  • IanesJsonHelper.toJson[IanesServer](array, IanesJsonHelper.toJson _)

  • :

    def toJson[T](source: Array[T])(toJson: Function[T, String]): String
    
    IanesJsonHelper.toJson(array)(IanesJsonHelper.toJson)
    

, , , , T, .

:

// doesn't compile - the compiler doesn't realize `_` is an Int and therefore doesn't know about the `+` operator
def map[A, B](xs: List[A], f: A => B) = ???
map(List(1,2,3), _ + 1)  

//compiles fine
def map[A, B](xs: List[A])(f: A => B) = ???
map(List(1,2,3))(_ + 1)

, .

Scala, Java #, LUB ( ) .

:

scala> def f[A](x: A, y: A): A = x
f: [A](x: A, y: A)A

scala> f(Some(1), None)
res0: Option[Int] = Some(1)

scala ( Some[Int] None), A (Option[Int] - LUB). scala , toJson .

#, , .

( 17, col 3): "Program.F(T, T)" . .

: LUBing , .

+5

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


All Articles