我正在尝试使用Scala编译器Y警告,但是我认为我做的不正确。在下面的示例中,未使用nums,因此我希望-Ywarn-value-discard为此显示警告。
如果有两个条件,则一个嵌套在另一个内部。孩子的情况与父母的情况完全相反,因此里面的任何内容都是无效代码。但是-Ywarn-dead-code不会对此发出警告。
有人可以建议我可能做错了什么吗?任何指针将不胜感激。
object DeadCodeWarn{
def main( args: Array[ String ] ) {
val nums = 1 to 100
//There should be a warning for squares
//as its a non-unit expression thats not
//used in any computation. Y-warn-value-discard
val squares = nums.map( x => x * x )
if( nums.length == 100 ){
println( "should be printed" )
if( nums.length !=100 )
{
//-Ywarn-dead-code
println( "Dead code, so should be warned against" )
}
}
}
}
$scalac -Xlint -Ywarn-all DeadCodeWarn.scala
静默成功。 最佳答案
-警告价值丢弃
该值不会被丢弃,而是分配给val
!
问题是val
未使用
使用代码:
package foo
case class Foo(x: Int) {
def foo: Int = {
val y = 2;
x
}
}
我得到了scalac 2.11.5和
-Ywarn-unused
:[warn] /.../foo.scala:5: local val in method foo is never used
[warn] val y = 2;
-Ywarn死代码
在常见逻辑不起作用的地方编写反例很容易:
// Evil mutable class
class Arrayish {
private var x: Int = 100
def length(): Int = {
val res = x
x += 1
res
}
}
def test(nums: Arrayish): Unit =
if (nums.length == 100) {
println( "should be printed" )
if (nums.length != 100) {
println("Dead code, so should be warned against")
}
}
死代码运行:
scala> test(new Arrayish())
should be printed
Dead code, so should be warned against
要么
class NonEqual {
def ==(x: Int): Boolean = true
def !=(x: Int): Boolean = true
}
class NaNLength {
val length: NonEqual = new NonEqual
}
def test2(nums: NaNLength): Unit =
if (nums.length == 100) {
println("should be printed")
if (nums.length != 100) {
println("Dead code, so should be warned against")
}
}
无效代码也会运行:
scala> test2(new NaNLength)
should be printed
Dead code, so should be warned against
Scalac编译器不够聪明,无法区分行为正常和行为异常的情况。
如果您要提交错误/功能请求,请提及以下示例:
def test3(nums: Array[Int]): Unit = {
if (true) {
println("should be printed")
if (false) {
println("Dead code, so should be warned against")
}
}
}
def test4(nums: Array[Int]): Unit = {
val hundred = nums.length == 100
if (hundred) {
println("should be printed")
if (!hundred) {
println("Dead code, so should be warned against")
}
}
}
scalac死代码报告器似乎不像例如Java。我希望scalac确实可以正确优化这些示例,但不要太复杂。