Last active
February 3, 2026 20:25
-
-
Save dacr/8db8b1273bbcee1173cf39e1936b3080 to your computer and use it in GitHub Desktop.
Collection operations / published by https://github.com/dacr/code-examples-manager #3783b8e4-99a6-44b4-b106-d06cd5646a96/4552c33de20124b9f1d207a448df587ce7a0587b
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // summary : Collection operations | |
| // keywords : scala, scalatest, collection, cheatsheet, @testable | |
| // publish : gist | |
| // authors : David Crosson | |
| // license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // id : 3783b8e4-99a6-44b4-b106-d06cd5646a96 | |
| // created-on : 2021-03-04T20:00:03Z | |
| // managed-by : https://github.com/dacr/code-examples-manager | |
| // run-with : scala-cli $file | |
| // --------------------- | |
| //> using scala "3.4.2" | |
| //> using dep "org.scalatest::scalatest:3.2.16" | |
| //> using objectWrapper | |
| // --------------------- | |
| import java.text.spi.DecimalFormatSymbolsProvider | |
| import java.text.{DecimalFormat, DecimalFormatSymbols, NumberFormat} | |
| import org.scalatest._ | |
| import flatspec._ | |
| import matchers._ | |
| class CollectionOperations extends AnyFlatSpec with should.Matchers { | |
| override def suiteName="CollectionOperations" | |
| // --------------------------------------------------------------------------------------------- | |
| "A collection" should "support safe get by index with lift" in { | |
| Array(42).lift(0) shouldBe Some(42) | |
| Array(42).lift(42) shouldBe None | |
| Array(42).lift(-42) shouldBe None | |
| List("a","b","c").lift(2) shouldBe Some("c") | |
| List("a","b","c").lift(42) shouldBe None | |
| List("a","b","c").lift(-42) shouldBe None | |
| } | |
| // --------------------------------------------------------------------------------------------- | |
| it should "replace any kind of loop without any constraint" in { | |
| info("iterator .iterate advantageously .from method as it fully generic") | |
| LazyList | |
| .iterate(10L)(_ + 1) | |
| .zip(Iterator.iterate(0L)(_ + 1)) | |
| .takeWhile{ case(value, index) => index < 5} | |
| .map{ case (value, index)=>value} | |
| .sum shouldBe 10+11+12+13+14 | |
| } | |
| // --------------------------------------------------------------------------------------------- | |
| } | |
| org.scalatest.tools.Runner.main(Array("-oDF", "-s", classOf[CollectionOperations].getName)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment