我们可以通过无形创建一个文字类型:
import shapeless.syntax.singleton._
var x = 42.narrow
// x: Int(42) = 42
Run Code Online (Sandbox Code Playgroud)
但是,Int(42)如果甚至无法创建类型别名,我如何作为一种类型进行操作
type Answ = Int(42) // won't compile
// or
def doSmth(value: Int(42)) = ... // won't compile
Run Code Online (Sandbox Code Playgroud) 我有3个特征
trait A
trait B
trait AB extends A with B
Run Code Online (Sandbox Code Playgroud)
和方法
def collect[E: Manifest](list: List[Any]) =
list flatMap {
case record: E => Some(record)
case _ => None
}
Run Code Online (Sandbox Code Playgroud)
对于给定的列表
val list = new A {} :: new A {} :: new A with B {} :: new AB {} :: Nil
Run Code Online (Sandbox Code Playgroud)
我collect用不同的类型调用
collect[A with B](list) // collect all elements from the list
collect[AB](list) // collect only the last element
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释行为A with B和AB类型的差异吗?
尽管被标记为重复,但这个问题仍然没有得到答复.
从http://www.scala-lang.org/files/archive/spec/2.12/08-pattern-matching.html#type-patterns我们可以写下面的代码
假设我有一个类型类:
trait T[A] {
def getType: String
}
object T {
def apply[A](implicit t: T[A]): T[A] = t
implicit object TInt extends T[Int] {
def getType = "Int"
}
implicit object TString extends T[String] {
def getType = "String"
}
}
Run Code Online (Sandbox Code Playgroud)
和使用我的类型类的类型化的类
class C[A] {
def func(implicit t: T[A]) = t.getType
}
Run Code Online (Sandbox Code Playgroud)
当我尝试典型时,C[A]我得到一个错误
val list: List[Int] = 1 :: 2 :: Nil
val result =
list match {
case list: List[t] => new C[t] …Run Code Online (Sandbox Code Playgroud) 假设我有一个没有参数的方法.如何确定类型参数的长度?
def func[T <: HList]: Nat = {
// some magic
}
Run Code Online (Sandbox Code Playgroud) 我偶然发现了一个意想不到的cats.effect.std.Mutex行为(它不适用于某些情况)。看来我错过了一些核心理解,Async但还没有找到根本原因。
进口:
\nimport cats.{Applicative, FlatMap}\nimport cats.effect.std.{Console, Mutex}\nimport cats.effect.*\nimport cats.implicits.*\nimport cats.syntax.all.*\n\nimport scala.concurrent.duration.*\nRun Code Online (Sandbox Code Playgroud)\n假设我们有一个服务
\n工作场景
\n class Service[F[_] : Async : FlatMap : Console](mutex: Mutex[F]) {\n def run(name: String): F[Unit] =\n for\n _ \xe2\x86\x90 Console[F].println(s"[$name] entered [run] within [${Thread.currentThread().getName}]")\n _ \xe2\x86\x90 mutex.lock.surround {\n for {\n _ \xe2\x86\x90 Console[F].println(s"[$name] entered [locked] within [${Thread.currentThread().getName}]")\n _ \xe2\x86\x90 Async[F].sleep(2.seconds)\n _ \xe2\x86\x90 Console[F].println(s"[$name] almost left [locked] within [${Thread.currentThread().getName}]")\n } yield ()\n }\n _ \xe2\x86\x90 Console[F].println(s"[$name] left [run] within [${Thread.currentThread().getName}]")\n …Run Code Online (Sandbox Code Playgroud)