How to convert a String to CharSequence?

后端 未结 5 717
别跟我提以往
别跟我提以往 2020-11-28 20:06

How to convert String to CharSequence in Java?

5条回答
  •  感动是毒
    2020-11-28 20:12

    Attempting to provide some (possible) context for OP's question by posting my own trouble. I'm working in Scala, but the error messages I'm getting all reference Java types, and the error message reads a lot like the compiler complaining that CharSequence is not a String. I confirmed in the source code that String implements the CharSequence interface, but the error message draws attention to the difference between String and CharSequence while hiding the real source of the trouble:

    scala> cols
    res8: Iterable[String] = List(Item, a, b)
    
    scala> val header = String.join(",", cols)
    :13: error: overloaded method value join with alternatives:
      (x$1: CharSequence,x$2: java.lang.Iterable[_ <: CharSequence])String 
      (x$1: CharSequence,x$2: CharSequence*)String
     cannot be applied to (String, Iterable[String])
           val header = String.join(",", cols)
    

    I was able to fix this problem with the realization that the problem wasn't String / CharSequence, but rather a mismatch between java.lang.Iterable and Scala's built-in Iterable.

    scala> val header = String.join(",", coll: _*)
    header: String = Item,a,b
    

    My particular problem can also be solved via the answers at Scala: join an iterable of strings

    In summary, OP and others who come across similar problems should parse the error messages very closely and see what other type conversions might be involved.

提交回复
热议问题