incognito.programmer | 31 Jan 17:50 2015
Picon

Combinators

I started reading Scala in Action as my first Scala book (I've come to realize this book is way too advanced for beginners, i am struggling mightily). 

I need help with the following. 

object Combinators {
  implicit def kestrel[A](a: A) = new {
    def tap(sideEffect: A => Unit): A = {
      sideEffect(a)
      a
    }
  }
}

case class Person(firstName: String, lastName: String)
case class Mailer(mailAddress: String) {
  def mail(body: String) = {
    println("send mail here...")
  }
}

object Main {
  import Combinators._
  def main(args: Array[String]): Unit = {
    Person("Nilanjan", "Raychaudhuri").tap(p => {
      println("First name " + p.firstName)
      Mailer("some address").mail("new person joined " + p)
    }).lastName
  }
}

My questions are as follows:
1) How does Person automatically get access to "tap"? 
 2) What does the implicit keyword do here? (am guessing this might answer q #1)
3) Any other book suggestions for a Java guy trying to learn Scala. (I've got about 10 years of Java experience, if that helps).

Thanks in advance. 

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Jim Newsham | 31 Jan 03:03 2015
Picon

code compiles under scala 2.11.4 but not 2.11.5


I had some code which compiled fine with scala 2.11.4 and then fails to compile under scala 2.11.5.  I distilled the problem down to a fairly simple example and posted it at https://groups.google.com/forum/#!topic/scalaquery/LrHthnKqGZY since the code was slick-related.  They suggested it might be a compiler regression and suggested I ask here.  Any comments?

Thanks,
Jim

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Haoyi Li | 24 Jan 20:07 2015
Picon

Why does for(x <- c; y = ...) yield {...} become c.map(x => (x, ...)).map((x,y) => {...})

I've been looking at http://docs.scala-lang.org/tutorials/FAQ/yield.html, and found this

for(x <- c; y = ...) yield {...} is translated into c.map(x => (x, ...)).map((x,y) => {...})

This seems rather odd to me. Why not

for(x <- c; y = ...) yield {...} is translated into c.flatMap{ x => val y = ...; {...} }

Isn't this basically the same, but much more straightforward?

The reason I bumped into this is that I was trying to implement a bunch of custom for-comprehension generators, and it kept asking for .map, and I couldn't figure out why. These were pretty odd generators, e.g. a TryCatch generator which you can put anywhere in your loop and which propagates a Seq() back up if it catches an exception, and so don't really have meaningful values to pass into map or flatMaps.

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Yevgeniy Mordovkin | 19 Jan 20:20 2015
Picon

Incremental compilation on Windows - new .class files added

Hi there. We compile using SBT, used Maven before and in both cases we ran into "Enclosing method not found" error while running code that was build after a few incremental builds. Upon investigation I found that the broken incremental jars contain some internal classes that do not exist for a clean compilation, that fall in Class.java on attempt to find the enclosing method. Did someone run into a similar issue?

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Jacek | 15 Jan 11:34 2015
Picon

Memory leak in LinkedHasMap and LinkedHashSet

Hi,

The clear() method in scala.collection.mutable.LinkedHashSet and scala.collection.mutable.LinkedHashMap does not set lastEntry to null.
In result it holds a reference to an object that was removed from the collection.
I don't see any reason for that behavior and consider it a bug.
Am I right?

Jacek 

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Dominik Sienkiewicz | 14 Jan 21:39 2015
Picon

Sample code for adding posts to FB from Play Framework Java/Scala or Scala only

I am looking for sample code for Play Framework Java/Scala or Scala only, where You can add post on FB.
I do not mean the authentication but when user already authenticated on my app by FB account that he could add to on his FB profile posts from my application.

In Spring MVC is trivial.
Spring Social give all You need.
Does anyone know where to find or want to share a working example of such solution?
Thanks in advance for Your help.

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Fiery | 14 Jan 21:08 2015
Picon

Why not use colon instead of "extends"?

Just one of my thinking being around there for quite a while about extending the concise style of other part of Scala language specs, "extends" just looks verbose and I personally took it as one typical Java expression.
I admit that I got too tried of Java's verbosity and I feel very much excited about making changes thru Scala's expressiveness and simplicity.

Just take a look at languages that considered more modern, like Python:

class sub_class(super_class) .....

like Ruby:
class SubClass < SuperClass .....

these are languages from which Scala get some of the syntax inspiration.

Plus, using colon makes it look more consistent with Scala's type system:

val word: String = "Hello"
var iter : Int = 1
def func : String = "I am a string"
val func : Int = { num : Int => num }

and take a look at what it will be like if use colon to replace extends:

class MoreString(val more : String, val count : Int) : String {.........}

I like using "with" to differentiate trait from class, here is how to mixin traits.
class MoreStrongString(val more : String, val count : Int) : String with StrongFeature {.........}


I understand that colons in Scala means slightly differently as what I suggest with class inheritance, but look at function result type, it's also a little different from the type for val/var. So there is nothing to lose with a more beautifully simple and clean world.

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Toby | 12 Jan 10:59 2015

Recursive Types (F-Bounded Polymporhism) and Java Interop

Hi,

I have found what I consider to be an inconsistency in the compiler and specifically how it interoperates with Java. I am using scala 2.11.5 and java 1.8.

A brief summary, full example below:

I have a java interface of the form

interface Upper<T extends <Upper<T>>

If a java method returns Upper<?>, the Scala compiler correctly interprets this as Upper[_$1] forSome { type _$1 <: Upper[_$1] }

However, a java interface with a method that accepts Upper<?> as an argument, implemented in Scala, must accept the argument as Upper[_], which expands to Upper[Any] and loses the recursiveness of the type.

I was for example not able to write the method as 

def consume(upper: Upper[T] forSome {type T <: Upper[T]})

even though that is really what the Java version means.

Full example below (a Java and a Scala class), any comments/thoughts/explanations and particularly solutions much appreciated.

Java:
public class TestRecursiveTypes
{
// Base interface for F-Bounded polymorphism
public interface Upper<T extends Upper<T>>
{
public T map();
}
// Implementation of F-Bounded polymorphism
public static class UpperImpl implements Upper<UpperImpl>
{
<at> Override
public UpperImpl map()
{
System.out.println(String.format("map <at> %s",this));
return new UpperImpl();
}
}
// Consumer interface
public interface UpperConsumer
{
void consume(Upper<?> upper_);
}
// Consumer implementation
public static class Consumer implements UpperConsumer
{
<at> Override
public void consume(Upper<?> upper_)
{
upper_.map().map().map();
}
}
// Upper factory method, returns interface
public Upper<?> provideUpper() 
{
return new UpperImpl();
}
public static void main(String[] args)
{
new TestRecursiveTypes().run();
}

private void run()
{
Upper<?> upper = new UpperImpl();
// This is also an upper, without conversio
Upper<?> mapped = upper.map();
Upper<?> upper2 = provideUpper();
new Consumer().consume(upper2.map().map().map());
}
}

Scala (does not compile for reasons explained above):

import TestRecursiveTypes._

import language.existentials

object TestRecursiveTypesScala {
  
  def main(args: Array[String]): Unit = {
    val impl = new UpperImpl()
    
    impl.map().map().map()
   
    val upper = new TestRecursiveTypes().provideUpper()
    
    upper.map().map().map()
  }
  
  class Consumer extends UpperConsumer {
    def consume(upper: Upper[_]): Unit = {
      upper.map().map()
    }
  }
}

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Rado Buransk√Ĺ | 12 Jan 10:33 2015
Picon

Upper bound for a type parameter and underscore

Can anybody point me to Scala language specification document where meaning of underscore as a type parameter is defined?

The following code doesn't compile. I don't have a real issue, so you don't need to tell me how to avoid it. I would expect that if there is an upper bound defined, then it is taken into account in this case.

trait Upper {
 
def up: Int
}

trait Underscore[T <: Upper] {
 
def t: T
}

object Underscore {
 
// This doesn't compile, beacuse "value up is not a member of _$1", even thoug there is the upper bound.
  def f(u: Underscore[_]) = u.t.up
}

Inspired by this question: http://stackoverflow.com/questions/27890745/f-bounded-polymorphic-return-types-in-scala/27891422

Thanks

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
alan.johnson | 9 Jan 21:24 2015

Object mixins

Fairly often, I've run into situations where I essentially want to create an object from a prexisting object of another type. This has come up in a number of circumstances. I may want to plug in some functionality from one object into a larger component. Or I might want to make the resulting object an adapter of the first object.

I realize that composition is one approach to this, necessitating every access to the wrapped object be routed through a member in the wrapper object containing the latter. Some might argue that this method is all that's ever needed.

But I was wondering is their anything theoretically wrong with the idea of mixing a previously instantiated object into an anonymous object?

It's common with cake pattern to do something like:

trait Mixin { val foo = "Hello" }

class Widget {
 
self: Mixin =>

 
def myMethod = foo.toUpperCase

}

val x
= new Widget with Mixin

And then Widget is a Mixin, inheriting all its functionality.

Is there anything theoretically wrong with:

trait Mixin { def foo: String }

class Widget {
 
self: Mixin =>

 
def myMethod = foo.toUpperCase

}

val mixinInstance
= new Mixin { val foo = "Hello2" }
val x
= new Widget with mixinInstance

I realize of course that `with` is an operator on types, but could there be an equivalent operator for mixing in values? As long as you know the instance fulfills the interface of some type, it seems like it could be treated the same way as a trait mixin, regarding rules for overlapping namespaces and such. I'm sure there's plenty of ways to abuse this concept, but the big benefit to me would be run-time plugging in of implementations of trait behavior.

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Jaap Taal | 8 Jan 18:45 2015
Picon

ambiguous implicit values when using contravariant generic type

Hi there,

I've run into a problem with inferImplicitValue in a scala macro. I was playing around with a macro for play's json libary `Format[T]`.
I could narrow it down to a problem how `Writes[T]` is sometimes implemented with `OWrites[T]`. Together with an explicit type declaration on
an `implicit val`, this led to the following compiler error.

    [error] ambiguous implicit values:
    [error]  both value xm in object TestTest of type => OMaterializer[X]
    [error]  and value tm in object TestTest of type => Materializer[T]
    [error]  match expected type Materializer[X]
    [error] one error found
    [error] (root/compile:compile) Compilation failed
    
Let's look at the code (the SBT project can be found here, https://github.com/q42jaap/scala-macro-inferImplicitValue )

    // models play json lib's Writes
    trait Materializer[-T]
    
    // models play json lib's OWrites
    trait OMaterializer[T] extends Materializer[T]

    trait T
    case class X() extends T
    
    object TestTest {
      // The OMaterializer trait here is the second part of the problem
      implicit val xm = new OMaterializer[X] {}
      // the explicit `tm: Materializer[T]` type declaration here is first part of the problem
      implicit val tm: Materializer[T] = Macro.genMaterializer[T, X]
    }

    object Macro {
      def genMaterializer[T, M]: Materializer[T] = macro MacroImpl.genMaterializer[T, M]
    }

    object MacroImpl {
      def genMaterializer[T: c.WeakTypeTag, M: c.WeakTypeTag](c: blackbox.Context): c.Expr[Materializer[T]] = {
        val tMaterializerTpe = c.universe.appliedType(c.typeOf[Materializer[_]], c.weakTypeOf[M])
        c.inferImplicitValue(tMaterializerTpe)
        c.universe.reify {
          new Materializer[T] {}
        }
      }
    }

Note the explicit type declaration for `tm`, removing it, fixes the issue. When `xm` is `Materializer[X]` instead of `OMaterializer[X]`, it also works.

`inferImplicitValue` considers both `tm` and `xm` when looking for a `Materializer[X]`. When `xm` is of the type `Materializer[X]` and `tm` has the type
`Materializer[T]` the inferer prefers `xm` over `tm`, because it's an exact match. But when `xm` is `OMaterializer[X]` the compiler cannot decide anymore which one
is better and throws an error.

As I said removing the explicit type declaration from `tm` fixes the problem, because at the time when the macro is executed only `xm`'s type is known.

Can I solve this problem `inferImplicitValue` has? The `silent` option is already true (by default).

In my real use case, I have multiple implementations of `T` (`X`, `Y`, `Z`) and pass then with a union type (like reactivemongo does) to the Macro:

    genMaterializer[T, Union[X \/ Y \/ Z]]

So I have to use the inferImplicitValue to find a Materializer for X, Y and Z.



Note that I have further simplified this case to

    object ThisDoesntWorkToo {
      implicit val xm = new OMaterializer[X] {}

      implicit val tm: Materializer[T] = withoutMacro[X]

      def withoutMacro[A](implicit m: Materializer[A]): Materializer[A] = m
    }

which doesn't use macros, but has the same compiler error:

[error] TestTest.scala:15: ambiguous implicit values:
[error]  both value xm in object ThisWorks of type => OMaterializer[X]
[error]  and value tm in object ThisWorks of type => Materializer[T]
[error]  match expected type Materializer[X]
[error]   implicit val tm: Materializer[T] = withoutMacro[X]

This simplifies the case here, but still leaves me with the problem that a implementation of an implicit val can refer to itself.
The easy and obvious in the latter case is to explicitly provide the implicit value, but as argumented in the final version of the macro I need to use inferImplicitValue
because I have a list of types for which I have to find a Materializer.

--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-language+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Gmane