相关疑难解决方法(0)

如何定义"类型析取"(联合类型)?

已经一个方法被提出来处理的重载方法双定义是,以取代与模式匹配超载:

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)

scala

175
推荐指数
12
解决办法
4万
查看次数

如何在Scala中设置多个类型边界?

我希望能够声明这样的东西:

trait Narrowable[A] extends Iterable[A] {

    def narrow[B <: A & B <: AnyRef] : Iterable[B]

}
Run Code Online (Sandbox Code Playgroud)

它的类型B应该是既有的亚型A AnyRef.这可能吗?

generics scala

67
推荐指数
1
解决办法
1万
查看次数

Scala双重定义(2种方法具有相同类型的擦除)

我在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]

谢谢.

scala overloading compilation typeclass type-erasure

67
推荐指数
6
解决办法
1万
查看次数

Scala:"使用"功能

我已经定义了'使用'功能如下:

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)

scala tuples using

30
推荐指数
4
解决办法
2万
查看次数

将Scala类型限制为一组类型之一

有没有办法定义一个泛型类型参数,它可以是一小组类型之一?我想定义一个类型T,它只能是{Int,Long,Float,Double}之一.

generics scala

7
推荐指数
1
解决办法
716
查看次数