Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Scala 3中,除了隐式之外,还有什么方法可以拉皮条呢?_Scala_Extension Methods_Implicit_Scala 3 - Fatal编程技术网

在Scala 3中,除了隐式之外,还有什么方法可以拉皮条呢?

在Scala 3中,除了隐式之外,还有什么方法可以拉皮条呢?,scala,extension-methods,implicit,scala-3,Scala,Extension Methods,Implicit,Scala 3,有没有办法在scala 3中拉皮条?因为它将在scala 3中被删除 那么,有没有办法用给定和使用来实现这一点呢 在scala 2中,我通常会这样做: implicit class ListOps[T](list: List[T]) { // just for the sake of example def myFlatMap(f: T => List[T]): List[T] = { if (this.list.tail.isEmpty) f(this.list.head

有没有办法在scala 3中拉皮条?因为它将在scala 3中被删除 那么,有没有办法用给定和使用来实现这一点呢

在scala 2中,我通常会这样做:

implicit class ListOps[T](list: List[T]) {
  // just for the sake of example
  def myFlatMap(f: T => List[T]): List[T] = {
    if (this.list.tail.isEmpty) f(this.list.head)
    else f(this.list.head) ++ this.list.tail.myFlatMap(f)
  }
}

在Scala 3中,隐式元素没有被删除,它们只是被赋予了+使用

您可以通过Scala 3-way引入扩展方法来创建库

extension [T](list: List[T]) def myFlatMap(f: T => List[T]): List[T] = {
  if (list.tail.isEmpty) f(list.head)
  else f(list.head) ++ list.tail.myFlatMap(f)
}
或者通过类+隐式转换模拟Scala 2-way

import scala.language.implicitConversions
 
class ListOps[T](list: List[T]) {
  def myFlatMap(f: T => List[T]): List[T] = {
    if (this.list.tail.isEmpty) f(this.list.head)
    else f(this.list.head) ++ this.list.tail.myFlatMap(f)
  }
}

given [T] as Conversion[List[T], ListOps[T]] = ListOps(_)
其实

implicit class ListOps[T](list: List[T]) {
  def myFlatMap(f: T => List[T]): List[T] = {
    if (this.list.tail.isEmpty) f(this.list.head)
    else f(this.list.head) ++ this.list.tail.myFlatMap(f)
  }
}

仍然有效。

在Scala 3中,隐式元素没有被删除,它们只是被赋予+使用

您可以通过Scala 3-way引入扩展方法来创建库

extension [T](list: List[T]) def myFlatMap(f: T => List[T]): List[T] = {
  if (list.tail.isEmpty) f(list.head)
  else f(list.head) ++ list.tail.myFlatMap(f)
}
或者通过类+隐式转换模拟Scala 2-way

import scala.language.implicitConversions
 
class ListOps[T](list: List[T]) {
  def myFlatMap(f: T => List[T]): List[T] = {
    if (this.list.tail.isEmpty) f(this.list.head)
    else f(this.list.head) ++ this.list.tail.myFlatMap(f)
  }
}

given [T] as Conversion[List[T], ListOps[T]] = ListOps(_)
其实

implicit class ListOps[T](list: List[T]) {
  def myFlatMap(f: T => List[T]): List[T] = {
    if (this.list.tail.isEmpty) f(this.list.head)
    else f(this.list.head) ++ this.list.tail.myFlatMap(f)
  }
}

仍然有效。

@DmytroMitin谢谢!请注意,这种模式通常称为扩展方法,您可以在官方Dotty文档中找到它们:@DmytroMitin谢谢!请注意,此模式通常称为扩展方法,您可以在官方Dotty文档中找到它们: