Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

java - Overloaded method value toString with alternatives

Java code

String method1(Object obj) {
  if (obj == null) {
    return "null";
  } else if (obj instanceof MyClass123[]) {
    return method2(ob)).toString();
  } else if (obj instanceof int[]) {
    return Arrays.toString((int[]) obj);
  } else if // and so for double, float, boolean, long, short...

  } else if (obj instanceof Object[]) {
    return Arrays.deepToString((Object[]) obj);
  } else {
    return obj.toString();
  }
}

My attempt to do the same in Scala

def method1(obj: Any): String = obj match {
    case null => "null"
    case x: Array[MyClass123] => method2(x).toString
    case x: Array[AnyRef] => Arrays.deepToString(x)
    case x: Array[_] => Arrays.toString(x)
  }

The last line causes the error of

overloaded method value toString with alternatives:
[error]   (Array[java.lang.Object])java.lang.String <and>
[error]   (Array[Double])java.lang.String <and>
[error]   (Array[Float])java.lang.String <and>
[error]   (Array[Boolean])java.lang.String <and>
[error]   (Array[Byte])java.lang.String <and>
[error]   (Array[Char])java.lang.String <and>
[error]   (Array[Short])java.lang.String <and>
[error]   (Array[Int])java.lang.String <and>
[error]   (Array[Long])java.lang.String
[error]  cannot be applied to (Array[_])
[error]     case x: Array[_] => Arrays.toString(x)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error you're getting starts with the fact that java.util.Arrays has lots of different 'toString' methods and the scala compiler doesn't know which one to pick.

But the real issue is that _ can match any type including Any and we don't have a version of toString that will work with Any - in fact the most general version we have is for AnyRef i.e. Object, which you already match in the previous case. Although toString is defined for many subtypes of AnyVal it isn't defined for Unit

What you really want to use is the mkString method i.e.

def method1(obj: Any): String = obj match {
    case null => "null"
    case x: Array[AnyRef] => Arrays.deepToString(x)
    case x: Array[AnyVal] => x.mkString("[",",","]")
    case _ => obj.toString
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...