Skip to content

Instantly share code, notes, and snippets.

@aaabramov
Last active April 7, 2021 15:47
Show Gist options
  • Save aaabramov/be9eb28c9f7a8c4bb2c4c6064defeb39 to your computer and use it in GitHub Desktop.
Save aaabramov/be9eb28c9f7a8c4bb2c4c6064defeb39 to your computer and use it in GitHub Desktop.
Scala 0.asInstanceOf[B]
// Code example for https://stackoverflow.com/q/66989225/5091346
package com.github.aaabramov
import java.time.LocalDateTime
object Test extends App {
trait TestTrait[A] {
val data: Seq[A]
def reduceLeft[B >: A](op: (B, A) => B): B = {
object reducer extends Function1[A, Unit] {
var first = true
var acc: B = 0.asInstanceOf[B]
override def apply(x: A): Unit =
if (first) {
acc = x
first = false
}
else acc = op(acc, x)
}
data foreach reducer
reducer.acc
}
}
val res = new TestTrait[String] {
override val data: Seq[String] = Seq("1", "2", "3")
}.reduceLeft(_ + _)
println(res) // 123
def foo[A]: A = 1.asInstanceOf[A]
println(foo[String]) // 1
println(foo[LocalDateTime]) // 1
println(foo[LocalDateTime].getClass) // java.lang.Integer
println(0.asInstanceOf[String]) // Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment