5

I am attempting to convert a List[Either[Int]] to anEither[List[Int]] using traverse from cats.

Error

[error] StringCalculator.scala:19:15: value traverseU is not a member of List[String]
[error]       numList.traverseU(x => {

Code

  import cats.Semigroup
  import cats.syntax.traverse._
  import cats.implicits._


  val numList = numbers.split(',').toList
  numList.traverseU(x => {
      try {
          Right(x.toInt)
      } catch {
        case e: NumberFormatException => Left(0)
      }
    })
      .fold(
        x => {},
        x => {}
      )

I have tried the same with traverse instead of traverseU as well.

Config(for cats)

lazy val root = (project in file(".")).
  settings(
    inThisBuild(List(
      organization := "com.example",
      scalaVersion := "2.12.4",
      scalacOptions += "-Ypartial-unification",
      version      := "0.1.0-SNAPSHOT"
    )),
    name := "Hello",
    libraryDependencies += cats,
    libraryDependencies += scalaTest % Test
  )
vamsiampolu
  • 6,328
  • 19
  • 82
  • 183

2 Answers2

9

It should indeed be just traverse, as long as you're using a recent cats version (1.0.x), however, you can't import both cats.syntax and cats.implicits._ as they will conflict.

Unfortunately whenever the Scala compiler sees a conflict for implicits, it will give you a really unhelpful message.

Remove the cats.syntax import and it should work fine. For further information check out the import guide.

Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
3

You need only cats.implicits._. e.g.

import cats.implicits._

val numbers = "1,2,3"
val numList = numbers.split(',').toList
val lst = numList.traverse(x => scala.util.Try(x.toInt).toEither.leftMap(_ => 0))

println(lst)
Radu Gancea
  • 773
  • 10
  • 19