2017-09-26 19 views
0
class Demo 
{ 
    def m1(a: Float) 
    { 
     println("m1 Float-arg method"); 
    } 
} 

object Demo1  
{ 
    def main(args: Array[String]) 
    { 
     val demo = new Demo 

     demo.m1(10f) 
     demo.m1(65l) 
    } 
} 

輸出:通過傳遞Long值來調用方法時,爲什麼Float參數方法得到執行?

M1浮法精氨酸方法

M1浮法精氨酸方法

  1. 按照上面的例子,我打電話使用長值M1(65升)方法,但我沒有定義與長參數的m1方法,所以我預計錯誤,所以我預計錯誤,

  2. 但m1方法與Float參數方法得到執行m1(56l)方法打電話?

內部流動將如何?

任何人都可以解釋一下嗎?

由於

回答

3

Long.scala同伴對象存在的隱式轉換:

implicit def long2float(x: Long): Float = x.toFloat

另外在Predef.scala存在用於自動裝箱和autounboxing轉化:

implicit def long2Long(x: Long) = java.lang.Long.valueOf(x)

所以首先你的65l自動裝箱到Long(65),然後轉換爲Float

0

下面是Long實施Scala

object Long extends AnyValCompanion { 
    /** The smallest value representable as a Long. */ 
    final val MinValue = java.lang.Long.MIN_VALUE 

    /** The largest value representable as a Long. */ 
    final val MaxValue = java.lang.Long.MAX_VALUE 

    /** Transform a value type into a boxed reference type. 
    * 
    * Runtime implementation determined by `scala.runtime.BoxesRunTime.boxToLong`.   See [[https://github.com/scala/scala  src/library/scala/runtime/BoxesRunTime.java]]. 
    * 
    * @param x the Long to be boxed 
    * @return  a java.lang.Long offering `x` as its underlying value. 
    */ 
    def box(x: Long): java.lang.Long = java.lang.Long.valueOf(x) 

    /** Transform a boxed type into a value type. Note that this 
    * method is not typesafe: it accepts any Object, but will throw 
    * an exception if the argument is not a java.lang.Long. 
    * 
    * Runtime implementation determined by  `scala.runtime.BoxesRunTime.unboxToLong`. See [[https://github.com/scala/scala src/library/scala/runtime/BoxesRunTime.java]]. 
    * 
    * @param x the java.lang.Long to be unboxed. 
    * @throws  ClassCastException if the argument is not a java.lang.Long 
    * @return  the Long resulting from calling longValue() on `x` 
    */ 
    def unbox(x: java.lang.Object): Long =  x.asInstanceOf[java.lang.Long].longValue() 

    /** The String representation of the scala.Long companion object. */ 
    override def toString = "object scala.Long" 
    /** Language mandated coercions from Long to "wider" types. */ 
    import scala.language.implicitConversions 
    implicit def long2float(x: Long): Float = x.toFloat 
    implicit def long2double(x: Long): Double = x.toDouble 
} 

當你在最後看到的,有兩個隱含的方法。方法隱式地將long轉換爲float

當您向接受float的方法證明long時,此方法用於轉換。

相關問題