代码之家  ›  专栏  ›  技术社区  ›  Random42

另一个类的scala方法引用?

  •  2
  • Random42  · 技术社区  · 6 年前

    scala的方法引用如何工作? 假设有以下列表:

    val list12 = List(1, 2)
    val list012 = 0 :: list1 //insert at head
    val list123 = list1 :+ 3 //insert at end
    

    假设有一个高阶函数接受一个元素、一个列表,以及一个将元素添加到列表并返回新列表的函数:

    def append[T](e: T, list: List[T], fun: (List[T], T) => List[T]): List[T] = {
      fun(list, e)
    }
    

    如果要在本地定义这样的方法:

    def appendAtHead[T](list: List[T], e: T): List[T] = {
      e :: list
    }
    

    那么电话就简单了:

    append(0, list12, appendAtHead[Int])
    

    但是如何参考现有的方法 :: :+ 是吗?下面的调用不起作用(例如在Java中这样做):

    append(0, list12, List.::)
    append(3, list12, SeqLike.:+) 
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Alexey Romanov    6 年前

    append(0, list12, appendAtHead[Int]) Specification 6.26.5

    :: :+ List.:: :: is right-associative, which also allows to write _.::(_) in Scala

    append[Int](0, list12, (x, y) => y :: x) // or append(0, list12, (x: List[Int], y: Int) => y :: x)
    append[Int](3, list12, _ :+ _) 
    

    fun

    def append[T](e: T, list: List[T])(fun: (List[T], T) => List[T]): List[T] = ...
    
    append(0, list12)((x, y) => y :: x)
    append(3, list12)(_ :+ _) 
    
        2
  •  2
  •   Tim    6 年前

    append(0, list12, _.::(_))
    append(0, list12, _ :+ _)
    

    List.:: List ::