使用隐式的scala类型转换 - >强制执行类型检查

时间:2016-03-09 11:48:54

标签: scala sbt

这里有一些简单的代码和问题。

有没有办法告诉scala编译器,如果要应用此转换的类型不存在,那么编译时会出错!

我可以在sbt工具中看到警告,但看不到任何描述如此战争。

 #include <stdlib.h>    /*  declares malloc(), realloc(), free(), etc */

 /*   and in a function somewhere */

 ItemType x = malloc(25);

  /*   can use any operations that do not copy more than 24 characters to x  */
  /*  but if we want a larger string, we have to manage it   */

  ItemType temp = realloc(50);

  if (temp == NULL)   /*  reallocation failed */
  {
       /* work out how to recover or terminate */
  }
  else
  {
       x = temp;
  } 

   /*  If reallocation failed and no recovery is done, do not execute the following code */

  /* can now treat x as an array of 50 characters (i.e. if we ensure strlen(x) never exceeds 49 */


  free(x);    /*  when we are done with x */

1 个答案:

答案 0 :(得分:2)

Scala编译器已经这样做了。

这是一个示例文件test.scala,尝试进行不可用的隐式转换:

class A(val n: Int) {
  def +(other: A) = new A(n + other.n)
}

object A {
  implicit def fromMyInt(n: Int) = new A(n)

  def main(args: Array[String]) = {
    println(1 + new A(1))
    println(1.0 + new A(1))
  }
}

尝试编译它会产生错误:

➤ scalac test.scala
test.scala:10: error: overloaded method value + with alternatives:
  (x: Double)Double <and>
  (x: Float)Double <and>
  (x: Long)Double <and>
  (x: Int)Double <and>
  (x: Char)Double <and>
  (x: Short)Double <and>
  (x: Byte)Double <and>
  (x: String)String
 cannot be applied to (A)
    println(1.0 + new A(1))
                ^
one error found