scala.collection.GenTraversableOnce Scala Examples

The following examples show how to use scala.collection.GenTraversableOnce. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: MapKOps.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.lf.data

import scala.language.higherKinds
import scala.collection.GenTraversableOnce
import scala.collection.immutable.{Map, MapLike}


trait MapKOps[K, +V, +This[+TV] <: Map[K, TV] with MapKOps[K, TV, This]]
    extends MapLike[K, V, This[V]] { this: This[V] =>
  override def updated[V1 >: V](key: K, value: V1): This[V1] = this + ((key, value))
  override def +[V1 >: V](kv: (K, V1)): This[V1]
  override def +[V1 >: V](elem1: (K, V1), elem2: (K, V1), elems: (K, V1)*): This[V1] =
    this + elem1 + elem2 ++ elems
  override def ++[V1 >: V](xs: GenTraversableOnce[(K, V1)]): This[V1] =
    xs.seq.foldLeft(this: This[V1])(_ + _)
} 
Example 2
Source File: Functional.scala    From jvm-toxcore-api   with GNU General Public License v3.0 5 votes vote down vote up
package im.tox.core

import scala.collection.GenTraversableOnce
import im.tox.core.typesafe.{ -\/, \/, \/- }


  def foldDisjunctionList[A, B](list: GenTraversableOnce[A \/ B]): A \/ List[B] = {
    list.foldLeft(\/-(Nil): A \/ List[B]) {
      (list, element) =>
        for {
          list <- list
          element <- element
        } yield {
          element :: list
        }
    }
  }

} 
Example 3
Source File: package.scala    From sbt-whitesource   with Apache License 2.0 5 votes vote down vote up
package sbtwhitesource

import scala.collection.GenTraversableOnce
import scala.collection.mutable

object `package` {
  implicit class KeyByAndMergeSyntax[A](val _xs: GenTraversableOnce[A]) extends AnyVal {
    
    def keyByAndMerge[K](keyFn: A => K, merge: (A, A) => Option[A]): Map[K, A] = {
      val m = mutable.Map.empty[K, A]
      for (elem <- _xs) {
        val key = keyFn(elem)
        val value = m get key match {
          case None    => elem
          case Some(a) =>
            merge(a, elem) getOrElse
              (sys error s"Multiple elements for the same key $key:\n\t$a\n\t$elem")
        }
        m(key) = value
      }
      m.toMap
    }
  }
} 
Example 4
Source File: ListWrapper.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.monads

import scala.collection.GenTraversableOnce

case class ListWrapper(list: List[Int]) {

  // just wrap
  def map[B](f: Int => B): List[B] = list.map(f)
  
  // just wrap
  def flatMap[B](f: Int => GenTraversableOnce[B]): List[B] = list.flatMap(f)
}

object ForComprehensionWithLists {
  def main(args: Array[String]): Unit = {
    val l1 = List(1, 2, 3, 4)
    val l2 = List(5, 6, 7, 8)
    val result = for {
      x <- l1
      y <- l2
    } yield x * y
    // same as
    // val result  = l1.flatMap(i => l2.map(_ * i))
    System.out.println(s"The result is: ${result}")
  }
}


object ForComprehensionWithObjects {
  def main(args: Array[String]): Unit = {
    val wrapper1 = ListWrapper(List(1, 2, 3, 4))
    val wrapper2 = ListWrapper(List(5, 6, 7, 8))
    val result = for {
      x <- wrapper1
      y <- wrapper2
    } yield x * y
    System.out.println(s"The result is: ${result}")
  }
} 
Example 5
Source File: ListWrapper.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.monads

import scala.collection.GenTraversableOnce

case class ListWrapper(list: List[Int]) {

  // just wrap
  def map[B](f: Int => B): List[B] = list.map(f)
  
  // just wrap
  def flatMap[B](f: Int => GenTraversableOnce[B]): List[B] = list.flatMap(f)
}

object ForComprehensionWithLists {
  def main(args: Array[String]): Unit = {
    val l1 = List(1, 2, 3, 4)
    val l2 = List(5, 6, 7, 8)
    val result = for {
      x <- l1
      y <- l2
    } yield x * y
    // same as
    // val result  = l1.flatMap(i => l2.map(_ * i))
    System.out.println(s"The result is: ${result}")
  }
}


object ForComprehensionWithObjects {
  def main(args: Array[String]): Unit = {
    val wrapper1 = ListWrapper(List(1, 2, 3, 4))
    val wrapper2 = ListWrapper(List(5, 6, 7, 8))
    val result = for {
      x <- wrapper1
      y <- wrapper2
    } yield x * y
    System.out.println(s"The result is: ${result}")
  }
} 
Example 6
Source File: package.scala    From gatling-grpc   with Apache License 2.0 5 votes vote down vote up
package com.github.phisgr.gatling

import io.gatling.commons.validation.{Failure, Success, Validation}
import io.gatling.core.Predef.value2Expression
import io.gatling.core.session._
import scalapb.lenses.Lens._
import scalapb.lenses.{Lens, Mutation, Updatable}

import scala.collection.GenTraversableOnce

package object pb {

  implicit class EpxrLens[A, B](val l: Lens[A, B]) extends AnyVal {
    def :~(e: Expression[B]): Expression[Mutation[A]] = e.map(l := _)
    def modifyExpr(e: Expression[B => B]): Expression[Mutation[A]] = e.map(l.modify)
  }

  // When the container type is polymorphic, type inference does not work well
  implicit class EpxrSeqLens[A, B](val l: Lens[A, Seq[B]]) extends AnyVal {
    private def ll = new EpxrSeqLikeLens(l)
    def :+~(e: Expression[B]): Expression[Mutation[A]] = ll :+~ e
    def :++~(e: Expression[GenTraversableOnce[B]]): Expression[Mutation[A]] = ll :++~ e
    def foreachExpr(f: Lens[B, B] => Expression[Mutation[B]]): Expression[Mutation[A]] = ll.foreachExpr(f)
  }

  implicit class EpxrSeqLikeLens[A, B, Coll[B] <: collection.SeqLike[B, Coll[B]]](
    val l: Lens[A, Coll[B]]
  ) extends AnyVal {
    type CBF = collection.generic.CanBuildFrom[Coll[B], B, Coll[B]]

    def :+~(e: Expression[B])(implicit cbf: CBF): Expression[Mutation[A]] =
      e.map(l :+= _)
    def :++~(e: Expression[GenTraversableOnce[B]])(implicit cbf: CBF): Expression[Mutation[A]] =
      e.map(l :++= _)
    def foreachExpr(f: Lens[B, B] => Expression[Mutation[B]])(implicit cbf: CBF): Expression[Mutation[A]] =
      f(Lens.unit).map(m => l.foreach(_ => m))
  }

  implicit class EpxrSetLens[A, B, Coll[B] <: collection.SetLike[B, Coll[B]] with Set[B]](
    val l: Lens[A, Coll[B]]
  ) extends AnyVal {
    type CBF = collection.generic.CanBuildFrom[Coll[B], B, Coll[B]]

    def :+~(e: Expression[B])(implicit cbf: CBF): Expression[Mutation[A]] =
      e.map(l :+= _)
    def :++~(e: Expression[GenTraversableOnce[B]])(implicit cbf: CBF): Expression[Mutation[A]] =
      e.map(l :++= _)
    def foreachExpr(f: Lens[B, B] => Expression[Mutation[B]])(implicit cbf: CBF): Expression[Mutation[A]] =
      f(Lens.unit).map(m => l.foreach(_ => m))
  }

  implicit class EpxrMapLens[A, K, V](
    val l: Lens[A, Map[K, V]]
  ) extends AnyVal {
    def :+~(e: Expression[(K, V)]): Expression[Mutation[A]] =
      e.map(l :+= _)
    def :++~(e: Expression[Iterable[(K, V)]]): Expression[Mutation[A]] =
      e.map(l :++= _)
    def foreachExpr(f: Lens[(K, V), (K, V)] => Expression[Mutation[(K, V)]]): Expression[Mutation[A]] =
      f(Lens.unit).map(m => l.foreach(_ => m))
    def foreachValueExpr(f: Lens[V, V] => Expression[Mutation[V]]): Expression[Mutation[A]] =
      f(Lens.unit).map(m => l.foreachValue(_ => m))
  }

  implicit class ExprUpdatable[A <: Updatable[A]](val e: Expression[A]) extends AnyVal {
    def updateExpr(mEs: (Lens[A, A] => Expression[Mutation[A]])*): Expression[A] = {
      val mutationExprs = mEs.map(_.apply(Lens.unit)).toArray
      val size = mutationExprs.length

      { s =>
        e(s) match {
          case Success(a) =>
            var result = a
            var i = 0
            var ret: Validation[A] = null
            do {
              if (i < size) {
                mutationExprs(i)(s) match {
                  case Success(mutation) =>
                    result = mutation(result)
                    i += 1
                  case f@Failure(_) =>
                    ret = f
                }
              } else {
                ret = Success(result)
              }
            } while (ret eq null)
            ret
          case f@Failure(_) => f
        }
      }
    }
  }

  implicit def value2ExprUpdatable[A <: Updatable[A]](e: A): ExprUpdatable[A] = new ExprUpdatable(value2Expression(e))

} 
Example 7
Source File: ByteStringBytes.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.compat.akka.impl

import java.io.OutputStream
import java.nio.charset.{CharacterCodingException, Charset}
import java.nio.{ByteBuffer, CharBuffer}
import java.util
import scala.annotation.tailrec
import scala.collection.GenTraversableOnce
import akka.util.ByteString
import swave.core.io.Bytes
import swave.core.macros._

class ByteStringBytes extends Bytes[ByteString] {

  ///////////////// CONSTRUCTION ///////////////////

  def empty = ByteString.empty
  def fill[A: Integral](size: Long)(byte: A) = {
    requireArg(0 <= size && size <= Int.MaxValue, "`size` must be >= 0 and <= Int.MaxValue")
    val b = implicitly[Integral[A]].toInt(byte).toByte
    apply(Array.fill(size.toInt)(b))
  }
  def apply(array: Array[Byte]) = ByteString(array)
  def apply(bytes: Array[Byte], offset: Int, length: Int) =
    ByteString(util.Arrays.copyOfRange(bytes, offset, offset + length))
  def apply[A: Integral](bytes: A*) = {
    val integral = implicitly[Integral[A]]
    val buf      = new Array[Byte](bytes.size)
    @tailrec def rec(ix: Int): ByteString =
      if (ix < buf.length) {
        buf(ix) = integral.toInt(bytes(ix)).toByte
        rec(ix + 1)
      } else view(buf)
    rec(0)
  }
  def apply(bytes: Vector[Byte])                  = ByteString(bytes: _*)
  def apply(buffer: ByteBuffer)                   = ByteString(buffer)
  def apply(bs: GenTraversableOnce[Byte])         = ByteString(bs.toArray)
  def view(bytes: Array[Byte])                    = ByteString(bytes) // no view-like constructor available on ByteStrings
  def view(bytes: ByteBuffer)                     = ByteString(bytes) // no view-like constructor available on ByteStrings
  def encodeString(str: String, charset: Charset) = ByteString(str, charset.name)
  def encodeStringStrict(str: String, charset: Charset) =
    try Right(ByteString(charset.newEncoder.encode(CharBuffer.wrap(str))))
    catch { case e: CharacterCodingException ⇒ Left(e) }

  ///////////////// QUERY ///////////////////

  def size(value: ByteString): Long = value.size.toLong
  def byteAt(value: ByteString, ix: Long): Byte = {
    requireArg(0 <= ix && ix <= Int.MaxValue, "`ix` must be >= 0 and <= Int.MaxValue")
    value(ix.toInt)
  }
  def indexOfSlice(value: ByteString, slice: ByteString, startIx: Long): Long = {
    requireArg(0 <= startIx && startIx <= Int.MaxValue, "`startIx` must be >= 0 and <= Int.MaxValue")
    value.indexOfSlice(slice, startIx.toInt).toLong
  }

  ///////////////// TRANSFORMATION TO ByteString ///////////////////

  def update(value: ByteString, ix: Long, byte: Byte) = concat(concat(take(value, ix), byte), drop(value, ix + 1))
  def concat(value: ByteString, other: ByteString)    = value ++ other
  def concat(value: ByteString, byte: Byte)           = value ++ ByteString(byte)
  def concat(byte: Byte, value: ByteString)           = ByteString(byte) ++ value
  def drop(value: ByteString, n: Long) = {
    requireArg(0 <= n && n <= Int.MaxValue, "`n` must be >= 0 and <= Int.MaxValue")
    value.drop(n.toInt)
  }
  def take(value: ByteString, n: Long) = {
    requireArg(0 <= n && n <= Int.MaxValue, "`n` must be >= 0 and <= Int.MaxValue")
    value.take(n.toInt)
  }
  def map(value: ByteString, f: Byte ⇒ Byte) = value.map(f)
  def reverse(value: ByteString)             = value.reverse
  def compact(value: ByteString)             = value.compact

  ///////////////// TRANSFORMATION TO OTHER TYPES ///////////////////

  def toArray(value: ByteString)                                   = value.toArray
  def copyToArray(value: ByteString, xs: Array[Byte], offset: Int) = value.copyToArray(xs, offset)
  def copyToArray(value: ByteString, sourceOffset: Long, xs: Array[Byte], destOffset: Int, len: Int) =
    drop(value, sourceOffset).copyToArray(xs, destOffset, len)
  def copyToBuffer(value: ByteString, buffer: ByteBuffer): Int = value.copyToBuffer(buffer)
  def copyToOutputStream(value: ByteString, s: OutputStream) = {
    @tailrec def rec(ix: Int, size: Int): Unit = if (ix < size) { s.write(value(ix).toInt); rec(ix + 1, size) }
    rec(0, value.size)
  }
  def toByteBuffer(value: ByteString)                   = value.toByteBuffer
  def toIndexedSeq(value: ByteString): IndexedSeq[Byte] = value
  def toSeq(value: ByteString): Seq[Byte]               = value
  def decodeString(value: ByteString, charset: Charset): Either[CharacterCodingException, String] =
    try Right(charset.newDecoder.decode(toByteBuffer(value)).toString)
    catch { case e: CharacterCodingException ⇒ Left(e) }

  ///////////////// ITERATION ///////////////////

  def foldLeft[A](value: ByteString, z: A, f: (A, Byte) ⇒ A)  = value.foldLeft(z)(f)
  def foldRight[A](value: ByteString, z: A, f: (Byte, A) ⇒ A) = value.foldRight(z)(f)
  def foreach(value: ByteString, f: Byte ⇒ Unit)              = value.foreach(f)

} 
Example 8
Source File: ByteVectorBytes.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.compat.scodec.impl

import java.io.OutputStream
import java.nio.ByteBuffer
import java.nio.charset.{CharacterCodingException, Charset}
import scala.collection.GenTraversableOnce
import scodec.bits.ByteVector
import swave.core.io.Bytes

class ByteVectorBytes extends Bytes[ByteVector] {

  ///////////////// CONSTRUCTION ///////////////////

  def empty                                               = ByteVector.empty
  def fill[A: Integral](size: Long)(byte: A)              = ByteVector.fill(size)(byte)
  def apply(array: Array[Byte])                           = ByteVector(array)
  def apply(bytes: Array[Byte], offset: Int, length: Int) = ByteVector(bytes, offset, length)
  def apply[A: Integral](bytes: A*)                       = ByteVector(bytes: _*)
  def apply(bytes: Vector[Byte])                          = ByteVector(bytes)
  def apply(buffer: ByteBuffer)                           = ByteVector(buffer)
  def apply(bs: GenTraversableOnce[Byte])                 = ByteVector(bs)
  def view(bytes: Array[Byte])                            = ByteVector(bytes)
  def view(bytes: ByteBuffer)                             = ByteVector(bytes)
  def encodeString(str: String, charset: Charset)         = if (str.isEmpty) empty else ByteVector(str getBytes charset)
  def encodeStringStrict(str: String, charset: Charset)   = ByteVector.encodeString(str)(charset)

  ///////////////// QUERY ///////////////////

  def size(value: ByteVector)                                           = value.size
  def byteAt(value: ByteVector, ix: Long)                               = value(ix)
  def indexOfSlice(value: ByteVector, slice: ByteVector, startIx: Long) = value.indexOfSlice(slice, startIx)

  ///////////////// TRANSFORMATION TO ByteVector ///////////////////

  def update(value: ByteVector, ix: Long, byte: Byte) = value.update(ix, byte)
  def concat(value: ByteVector, other: ByteVector)    = value ++ other
  def concat(value: ByteVector, byte: Byte)           = value :+ byte
  def concat(byte: Byte, value: ByteVector)           = byte +: value
  def drop(value: ByteVector, n: Long)                = value.drop(n)
  def take(value: ByteVector, n: Long)                = value.take(n)
  def map(value: ByteVector, f: Byte ⇒ Byte)          = value.map(f)
  def reverse(value: ByteVector)                      = value.reverse
  def compact(value: ByteVector)                      = value.compact

  ///////////////// TRANSFORMATION TO OTHER TYPES ///////////////////

  def toArray(value: ByteVector)                                   = value.toArray
  def copyToArray(value: ByteVector, xs: Array[Byte], offset: Int) = value.copyToArray(xs, offset)
  def copyToArray(value: ByteVector, sourceOffset: Long, xs: Array[Byte], destOffset: Int, len: Int) =
    value.copyToArray(xs, destOffset, sourceOffset, len)
  def copyToBuffer(value: ByteVector, buffer: ByteBuffer): Int = value.copyToBuffer(buffer)
  def copyToOutputStream(value: ByteVector, s: OutputStream)   = value.copyToStream(s)
  def toByteBuffer(value: ByteVector)                          = value.toByteBuffer
  def toIndexedSeq(value: ByteVector): IndexedSeq[Byte]        = value.toIndexedSeq
  def toSeq(value: ByteVector): Seq[Byte]                      = value.toSeq
  def decodeString(value: ByteVector, charset: Charset): Either[CharacterCodingException, String] =
    value.decodeString(charset)

  ///////////////// ITERATION ///////////////////

  def foldLeft[A](value: ByteVector, z: A, f: (A, Byte) ⇒ A)  = value.foldLeft(z)(f)
  def foldRight[A](value: ByteVector, z: A, f: (Byte, A) ⇒ A) = value.foldRight(z)(f)
  def foreach(value: ByteVector, f: Byte ⇒ Unit)              = value.foreach(f)

}