java.lang.Double vs scala.Double

1,780 views
Skip to first unread message

Michael Stover

unread,
Apr 6, 2012, 3:59:38 PM4/6/12
to scala-user
The following code fails at runtime:

class ArrayTest[T](val d: T) {

val cl = d.getClass()
println(cl)
val arrayCl = Array.fill(5)({ d })(Manifest.classType(cl)).getClass
println(arrayCl)

val arr = Array.fill(5)({
Array.fill(5)({
d
})(Manifest.classType(cl))
})(Manifest.classType(arrayCl))

def apply(i: Int) = arr(i)
}

object ArrayTest {

def main(args: Array[String]) = {
println(new ArrayTest[java.lang.Double](0.toDouble)(2).mkString("
"))
println(new ArrayTest[Double](0.toDouble)(2).mkString(" "))
}
}

Can anyone explain why it fails on the second line of main? And can
anyone tell me what to do that doesn't involve replacing every
instance of "Double" with "java.lang.Double" in my source code?
Message has been deleted

Thipor Kong

unread,
Apr 8, 2012, 4:15:22 AM4/8/12
to scala...@googlegroups.com
Don't know, if java.lang.Double[] should be automatically "unboxed" to double[].

I believe the idiomatic way is to retrieve Manifests implicitely; thus letting the compiler figuring out the right types (see section 7.4 of Scala Language spec).  This works

class ArrayTest[T: ClassManifest](val d: T) { 
  val arr = Array.fill(5)({Array.fill(5)({ d })})
  def apply(i: Int) = arr(i) 

object ArrayTest { 

  def main(args: Array[String]) = { 
    val at1 = new ArrayTest[java.lang.Double](0.toDouble)
    println(at1(2).mkString(" ")) 
    
    val at2 = new ArrayTest[Double](0.toDouble)
    println(at2(2).mkString(" ")) 
  } 
}
Reply all
Reply to author
Forward
0 new messages