Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  )
like image 817
vamsiampolu Avatar asked Jan 23 '18 21:01

vamsiampolu


2 Answers

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.

like image 163
Luka Jacobowitz Avatar answered Nov 19 '22 10:11

Luka Jacobowitz


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)
like image 44
Radu Gancea Avatar answered Nov 19 '22 11:11

Radu Gancea