vamsiampolu
vamsiampolu

Reputation: 6622

List[String] does not have a member traverse from cats

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
  )

Upvotes: 5

Views: 2017

Answers (2)

user804690
user804690

Reputation:

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)

Upvotes: 3

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23502

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.

Upvotes: 10

Related Questions