已经一个方法被提出来处理的重载方法双定义是,以取代与模式匹配超载:
object Bar {
def foo(xs: Any*) = xs foreach {
case _:String => println("str")
case _:Int => println("int")
case _ => throw new UglyRuntimeException()
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法要求我们放弃对参数的静态类型检查foo.能够写作会好得多
object Bar {
def foo(xs: (String or Int)*) = xs foreach {
case _: String => println("str")
case _: Int => println("int")
}
}
Run Code Online (Sandbox Code Playgroud)
我可以接近Either,但它有两种以上的快速变得难看:
type or[L,R] = Either[L,R]
implicit def l2Or[L,R](l: L): L or R = Left(l)
implicit def r2Or[L,R](r: R): L or R = …Run Code Online (Sandbox Code Playgroud) 我希望能够声明这样的东西:
trait Narrowable[A] extends Iterable[A] {
def narrow[B <: A & B <: AnyRef] : Iterable[B]
}
Run Code Online (Sandbox Code Playgroud)
它的类型B应该是既有的亚型A 和 AnyRef.这可能吗?
我在scala中写了这个,它不会编译:
class TestDoubleDef{
def foo(p:List[String]) = {}
def foo(p:List[Int]) = {}
}
Run Code Online (Sandbox Code Playgroud)
编译通知:
[error] double definition:
[error] method foo:(List[String])Unit and
[error] method foo:(List[Int])Unit at line 120
[error] have same type after erasure: (List)Unit
Run Code Online (Sandbox Code Playgroud)
我知道JVM没有对泛型的原生支持,所以我理解这个错误.
我可以写包装List[String],List[Int]但我很懒:)
我很怀疑,但是,有没有另一种方式表达List[String]不是同一种类型List[Int]?
谢谢.
我已经定义了'使用'功能如下:
def using[A, B <: {def close(): Unit}] (closeable: B) (f: B => A): A =
try { f(closeable) } finally { closeable.close() }
Run Code Online (Sandbox Code Playgroud)
我可以这样使用它:
using(new PrintWriter("sample.txt")){ out =>
out.println("hellow world!")
}
Run Code Online (Sandbox Code Playgroud)
现在我很好奇如何定义'使用'函数来获取任意数量的参数,并且能够单独访问它们:
using(new BufferedReader(new FileReader("in.txt")), new PrintWriter("out.txt")){ (in, out) =>
out.println(in.readLIne)
}
Run Code Online (Sandbox Code Playgroud) 有没有办法定义一个泛型类型参数,它可以是一小组类型之一?我想定义一个类型T,它只能是{Int,Long,Float,Double}之一.
scala ×5
generics ×2
compilation ×1
overloading ×1
tuples ×1
type-erasure ×1
typeclass ×1
using ×1