标签: implicit

scala:pimp我的库有重载

任何想法为什么没有以下工作?

implicit def listExtensions[A](xs : List[A]) = new ListExtensions(xs)
class ListExtensions[A](xs : List[A])
{
    def foreach[B](f: (A, Int) => B)
    {
        var i = 0;
        for (el <- xs)
        {
            f(el, i);
            i += 1;
        }
    }
}

var a = List(1, 2, 3);
a foreach { (el, i) => println(el, i) };
Run Code Online (Sandbox Code Playgroud)

当我用fsc 2.8.1编译它时,我得到以下错误:"错误的参数数量;期望= 1:foreach {(el,i)=> println(el,i)};".我做错了什么或者根本没有办法通过"皮条客我的图书馆"技巧添加重载方法?

PS我不知道如何实现foreach的iterate-with-current-index风格(我知道zipWithIndex方法),而是关于重载和隐式转换如何一起使用.

scala implicit

2
推荐指数
1
解决办法
671
查看次数

如何隐式使用函数?

嗨,我读了Debasish关于隐式函数的有趣帖子.我写了这段代码:

def find[C <: Business](id: String) = {
  collection.findOneByID(id).map(x=> implicitly[DBObject => C].apply(x))
}
Run Code Online (Sandbox Code Playgroud)

但它无法使用此编译器消息进行编译:

could not find implicit value for parameter e: (com.mongodb.casbah.commons.Imports.DBObject) => C
Run Code Online (Sandbox Code Playgroud)

我的错是什么?有人可以帮帮我吗?

UPDATE

我的想法是这样的:find是在一个特性中声明的,对DBObject一无所知,我不想把这个依赖.

 trait BusinessRepository {
   def find[C <: Business](id: String): Option[C]
 }

class MongoBusinessRepository {

  val collection = ..

  def find[C <: Business](id: String): Option[C] = {
    collection.findOneByID(id).map(x=> implicitly[DBObject => C].apply(x))         
  }

  implicit def DBObject2Hotel(x: DBObject): Hotel = {
    // ... 
    // returning Hotel
  }
}

case class Hotel(...) extends Business(...)
Run Code Online (Sandbox Code Playgroud)

scala implicit

2
推荐指数
1
解决办法
1021
查看次数

隐式键入与匿名类型

Implicitly Typed和Anonymous Type之间是否相同或有任何区别.如果它不同那么Implicitly Typed和Anonymous Type之间的主要区别是什么?

.net c# anonymous-types implicit

2
推荐指数
1
解决办法
1966
查看次数

隐式转换适用于符号但不适用于字符串

我正在研究DSL的一些正式的基于语法的东西.我希望能够说出一些代码'start produces "a" andThen 'b andThen "c",其中符号和字符串代表语法的不同组成部分.我看到这样的代码有问题:

class ImplicitTest {

  trait GrammarPart
  case class Nonterminal(name: Symbol) extends GrammarPart
  case class Terminal(value: String) extends GrammarPart


  case class Wrapper(production: Seq[GrammarPart]) {
    def andThen(next: Wrapper) =
      Wrapper(production ++ next.production)
  }

  implicit def symbolToWrapper(symbol: scala.Symbol) =
    Wrapper(Seq(Nonterminal(symbol)))

  implicit def stringToWrapper(s: String) =
    Wrapper(Seq(Terminal(s)))
}

object StringGrammar extends ImplicitTest {
  "x" andThen "y" // this causes a compiler error: "value andThen is not a member of String"
}

object SymbolGrammar extends ImplicitTest { …
Run Code Online (Sandbox Code Playgroud)

scala implicit

2
推荐指数
1
解决办法
157
查看次数

在Scala中省略括号

我正在使用隐式类进行一些实验,并提出了以下问题.这里是:

object Main extends App {
  implicit class IntExtractor(str: String){
    def extractInt(i: Int): Int = i + str.##
  }

  implicit class ArrayCreator(i: Int){
    def -->(ii: Int): Array[Int] = Array[Int](i, ii)
    def createArray(ii: Int): Array[Int] = Array[Int](i, ii) 
  }

  "STR" extractInt 10 createArray 11   //fine
  ("STR" extractInt 10) --> 11         //fine
  "STR" extractInt 10 --> 11           //compile-error
}
Run Code Online (Sandbox Code Playgroud)

DEMO

不用-->方法编译示例的原因是什么?我认为-->是一个完全有效的标识符Scala......就像任何其他标识符一样.

methods scala implicit

2
推荐指数
1
解决办法
84
查看次数

Scala中类型较高的类型类实例中的两个参数函数,如何将这个简单的Haskell代码转换为Scala?

以下Haskell代码:

main = putStrLn $ "bla " ++ (toStr (A 1) (A 2))
--main2 = putStrLn $ "bla " ++ (toStr (A 1) (A "String")) -- does not compile, as it should
main3 = putStrLn $ "bla " ++ (toStr (A "String") (A "String"))

data A a = A a deriving Show -- (1) data type declaration 

class C a where -- (2) type class declaration
   toStr :: a-> a->String

instance C (A a) where -- (3) instance declaration
   toStr …
Run Code Online (Sandbox Code Playgroud)

haskell scala implicit typeclass

2
推荐指数
1
解决办法
78
查看次数

从伴随对象导入隐式值但未使用

我写了一些代码,它在伴随对象中获取了一些隐含的值,如下所示:

package example.implicits

class Test {
  import Test.GetValue
  import Test.Implicits._

  val intV = getV[Int]
  val stringV = getV[String]

  private def getV[T](implicit getV: GetValue[T]): T = getV.value
}

object Test {
  trait GetValue[T] {
    def value: T
  }

  object Implicits {
    implicit val intValue = new GetValue[Int] {
      def value = 10
    }

    implicit val stringValue = new GetValue[String] {
      def value = "ten"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这段代码无法编译,编译器抱怨它无法找到所需的隐含值.请注意我的环境是

Java HotSpot(TM)64位服务器VM上的scala 2.11.8,Java 1.8.0_66

但是,如果我明确使用这些值,则没有错:

class Test {
  import Test.GetValue
  import Test.Implicits._

  val …
Run Code Online (Sandbox Code Playgroud)

scala implicit

2
推荐指数
1
解决办法
474
查看次数

通用值类

是否可以在scala中为某些定义值类Numeric[T]?我试过这样的事情:

case class Inches[T <: Numeric[T]](value: T)(implicit num: Numeric[T]) extends AnyVal
Run Code Online (Sandbox Code Playgroud)

但是我得到了编译错误value classes can have only one parameter.

有没有办法绕过这个?

先谢谢.

generics scala implicit

2
推荐指数
1
解决办法
116
查看次数

为什么Scala和sbt可以编译这段代码?

Scala工作表的示例

case class Test(name: String)

case class TestMapped(name: String,
                      otherProperty: String)

protected implicit def toTestMapped(test: Test): TestMapped = {
  TestMapped(name = test.name,
             otherProperty = test.otherProperty)
}

val test = Test(name = "bug")
val testMapped = toTestMapped(test)
Run Code Online (Sandbox Code Playgroud)

如果在类Test中不存在"otherProperty",为什么Scala和sbt可以编译这段代码?此代码以关键运行时错误结束:java.lang.StackOverflowError

但是,如果删除toTestMapped方法的"隐式",或者通过其他名称更改"otherProperty",则此代码不会编译.

我正在使用Scala 2.12.4.

scala compilation implicit sbt

2
推荐指数
1
解决办法
84
查看次数

`int main(i){printf(“ i =%d \ n”,i); 我的值为1。为什么?请解释?

为什么打印我的值为1,有人可以解释一下吗?

#include<stdio.h>
int main(i)
{ 
    printf("i = %d\n", i); 
}
Run Code Online (Sandbox Code Playgroud)

输出i = 1。

c initialization implicit

2
推荐指数
1
解决办法
78
查看次数