简体   繁体   中英

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

I am attempting to convert a List[Either[Int]] to an Either[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
  )

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.

You need only cats.implicits._ . eg

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM