can a var that is not named in the param be used as an arg when a function is called in the main? like in the following codes:
fun main() {
val firstNumber = 10
val secondNumber = 5
val thirdNumber = 8
val result = add(firstNumber, secondNumber)
val anotherResult = subtract(firstNumber, thirdNumber)
println("$firstNumber + $secondNumber = $result")
println("$firstNumber - $thirdNumber = $anotherResult")
}
fun add(firstNumber: Int, secondNumber: Int): Int {
return firstNumber + secondNumber
}
fun subtract(firstNumber: Int, secondNumber: Int): Int {
return firstNumber - secondNumber
}
thirdNumber is not a parameter in the two functions i.e add and subtract functions but was used as an argument in variable anotherResult().
i have run the code and i expect the code not to run but it runs
can a var that is not named in the param be used as an arg when a function is called in the main?
Yes, that is how variable and parameters work, at least in Kotlin.
Variables are just a way to give names to values, so you can refer to those values, reuse them, and understand their meaning better. They don't have to match the names of the parameters of the function you're calling.
You could make things even clearer by using named parameters, to show that you are using the value of an arbitrarily named variable as argument for a parameter of a different name:
val anotherResult = subtract(firstNumber = firstNumber, secondNumber = thirdNumber)
i have run the code and i expect the code not to run but it runs
Wouldn't you expect add(1, 2) to work? Those literal arguments don't have names, so they can't match the parameter names.
Related
I'm implementing external payment gateway. But Front controller does not show any changes in the frontoffice. Atleast it should throw some error(so it would be easy to understand) but instead it shows no changes.
I have tried deleting, again creating same file but i think there is something wrong with the code.
I'm a newbie in custom module development. Hopefully anybody can point me in right direction. A quick help would be really appreciated.
Please check my code below. Correct me if i missed something.
<?php
require_once dirname(__FILE__) . '/config/config.inc.php';
require_once dirname(__FILE__) . '/latpayredirect.php';
class LatpayRedirectValidationModuleFrontController extends ModuleFrontController
{
public $warning = '';
public $message = '';
public function initContent()
{
parent::initContent();
$this->context->smarty->assign(array(
'warning' => $this->warning,
'message' => $this->message
));
$this->setTemplate('module:latpayredirect/views/templates/front/payment_return.tpl');
}
public function postProcess()
{
ob_start();
$context = Context::getContext();
if (is_null($context->cart)) {
$context->cart = new Cart($context->cookie->id_cart);
}
if (is_null($context->cart->id_currency)) {
$context->cart->id_currency = $context->cookie->id_currency;
}
$cart = $this->context->cart;
$this->abrir("http://davivienda.com");
if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
Tools::redirect('index.php?controller=order&step=1');
}
$customer = new Customer($cart->id_customer);
if (!Validate::isLoadedObject($customer)) {
Tools::redirect('index.php?controller=order&step=1');
}
// $currency = $this->context->currency;
$currency = $cart->id_currency;
$total = (float)$cart->getOrderTotal(true, Cart::BOTH);
$object = new filemain();
$order = $object->methodCreateInMain($cart->id, Configuration::get('PS_OS_PAYMENT'), $total, $currency, $customer->secure_key);
//The order passes directly on paid status
$this->module->validateOrder((int)$cart->id, Configuration::get('PS_OS_PAYMENT'), $total, $this->module->displayName, null, array(), (int)$currency->id, false, $customer->secure_key);
Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)$cart->id.'&id_module='.(int)$this->module->id.'&id_order='.$this->module->currentOrder.'&key='.$customer->secure_key);
}
public function abrir($param)
{
echo" <script> window.open(URL,'ventana1,'width=300,height=300,scrollbars=NO')</script> ";
}
}
I have created a simple module as yours and the controller works fine. Please find the below code.
I think, something wrong with your class name & file name (try file name in lowercases, and controller class name should be like class )
/modules/latpayredirect/latpayredirect.php
<?php
class Latpayredirect extends PaymentModule
{
public function __construct()
{
$this->name = 'latpayredirect';
$this->author = 'abdullacm';
$this->version = '1.0.0';
$this->need_instance = 0;
parent::__construct();
$this->displayName = 'payment module';
$this->description = 'payment module';
}
}
/modules/latpayredirect/controllers/front/validation.php
<?php
class LatpayredirectValidationModuleFrontController extends ModuleFrontController
{
public function initContent()
{
echo 'from latpay validation front controller';
exit;
}
}
I had the same problem, and it appears that you cannot override controllers or classes from a module with the method you are using (even though they say it works in the documentation!).
The way that worked for me is to copy your override class (for instance here the override of the Order class) directly in the main file of the module:
<?php
class MyModule extends Module
{
}
class MyCustomOrder extends Order
{
}
?>
Good luck!
I'm learning Coroutines of Kotlin, I'm a beginner of running code online in https://try.kotlinlang.org/
I try to test Code A in the website, but I get many errors just like Image A, how can I fix it?
Code A
import kotlinx.coroutines.*
fun main(args: Array<String>) {
val job = launch {
val child = launch {
try {
delay(Long.MAX_VALUE)
} finally {
println("Child is cancelled")
}
}
yield()
println("Cancelling child")
child.cancel()
child.join()
yield()
println("Parent is not cancelled")
}
job.join()
}
Image A
Try to run following code:
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
fun main() = runBlocking<Unit> { //here i made change
val job = launch {
val child = launch {
try {
delay(Long.MAX_VALUE)
} finally {
println("Child is cancelled")
}
}
yield()
println("Cancelling child")
child.cancel()
child.join()
yield()
println("Parent is not cancelled")
}
job.join()
}
Output would be :)
Cancelling child
Child is cancelled
Parent is not cancelled
Why does this piece of Java code not compile in Kotlin without the explicit type parameter in Collectors.toList<String>()? Is there a more idiomatic way to do this?
// works
List<String> folders = Files.walk(Paths.get(args[0]))
.filter(it -> it.toFile().isDirectory())
.map(it -> it.toAbsolutePath().toString())
.collect(Collectors.toList());
// does not compile - resulting type is `MutableList<in String!>..List<Any?>?` which is not compatible to `List<String>`
val folders: List<String> = Files.walk(Paths.get(args[0]))
.filter { it.toFile().isDirectory }
.map { it.toAbsolutePath().toString() }
.collect(Collectors.toList())
// compiles
val folders: List<String> = Files.walk(Paths.get(args[0]))
.filter { it.toFile().isDirectory }
.map { it.toAbsolutePath().toString() }
.collect(Collectors.toList<String>())
Why does this piece of Java code not compile in Kotlin without the explicit type parameter in Collectors.toList<String>()?
This looks like a compiler bug to me. I recommend creating an issue in Kotlin (KT) | YouTrack.
Is there a more idiomatic way to do this?
Yes. As Kirill Rakhman comments, "Kotlin has its own File.walk extension method." e.g.:
val folders: List<String> = File(args[0]).walk()
.filter(File::isDirectory)
.map(File::getAbsolutePath)
.toList()
If you prefer using Java 8 streams then checkout Kotlin/kotlinx.support: Extension and top-level functions to use JDK7/JDK8 features in Kotlin 1.0. It defines a Stream<T>.toList() function:
val folders: List<String> = Files.walk(Paths.get(args[0]))
.filter { it.toFile().isDirectory }
.map { it.toAbsolutePath().toString() }
.toList()
I've found two ways to make it work without explicitly specifying generic type in both places.
Either you can specify full type of variable with generic covariance
val folders: MutableList<in String> = Files.walk(Paths.get(args[0]))
.filter { it.toFile().isDirectory }
.map { it.toAbsolutePath().toString() }
.collect(Collectors.toList())
or you can simply let Kotlin do its type inference for variable (not generic parameter of method)
val folders2 = Files.walk(Paths.get(args[0]))
.filter { it.toFile().isDirectory }
.map { it.toAbsolutePath().toString() }
.collect(Collectors.toList<String>())
In my program I have used an array of pointers as a structure variable to get first name and second name from the user.
The following is my function call statement:
ret_val = update_person(&ptr_person[person_index],f_name,s_name);
where ptr_person[SIZE] is a pointer variable and f_name and s_name are character array variables.
The following is my function definition where name_ret is int:
name_ret update_person(person_name_et **person,char *first_arg,char *second_arg)
{
int val = SUCCESS, val1 = SUCCESS,val2= SUCCESS;
int f_len = sizeof(first_arg);
int s_len = sizeof(second_arg);
val2 = remove_newline(first_arg);
val1 = remove_newline(second_arg);
val = allocate_person(person, f_len, s_len);
if((val && val1) == SUCCESS)
{
(*person)->first_name = first_arg;
(*person)->second_name = second_arg;
return SUCCESS;
}
else
{
return FAILURE;
}
}
The problem in the code is it works fine at the instance but when the function is called next iteration the ptr_Person[0] is replaced with ptr_person[1] and if we have 5 instances then all the 5 variables are replaced by the last values.
If I have a variable declared like var gameBoard: [Piece] = [], is there any way to add a subclass of Piece, called Queen, to the array?
I am using Piece to represent all pieces. Queen, Pawn, Bishop and such are all subclasses of Piece, and should be included on the board.
I remember doing this frequently in Objective C, where subclasses were able to be used in place of the superclass. But in my first attempts, it I am getting an error saying
'#lvalue $T11' is not identical to 'Piece`
Is this not possible anymore? Or would there need to be some use of generics that I cannot think of right now?
Edit
Here is the implementation of my board, including only the relevant parts.
struct GameBoard{
var board: [[Piece]]
init() {
board = []
for _ in 0...7{
var collumn: [Piece] = []
for _ in 0...7{
var piece = Piece(player: .None, board: self)
collumn.append(piece)
}
board.append(collumn)
}
}
subscript(coords:(Int, Int) ) -> Piece {
return board[coords.1][coords.0]
}
}
The code that fails is
var board = GameBoard()
var q = Queen(player: .Black, board: board)
board[(4,5)] = q //Throws the error
board.board[5][4] = q //Works
It seems to me that these two should work the same way. It may be an issue with the subscripting, but I am not completely sure.
Just to followup on your edits, this works fine in Swift. For example:
class Piece {}
class Bishop : Piece {}
let pieces: [Piece] = [Bishop()]
Do you have an example that does not work?
As a note, when you see #lvalue $T## in your errors, it often means you're trying to modify a constant. An easy way to make that mistake is to try to modify an array that was passed to you and that you did not mark var. For example, see Swift function that takes in array giving error: '#lvalue $T24' is not identical to 'CGFloat'.
Here is how I would write it. Includes answer to the question about subscripting, and for bonus, uses a Coords struct in place of tuples (allows implementation of Printable for example) and uses optionals for each square (allows nil to be used as the representation of an empty square.)
class Piece : Printable {
var description: String { get { return "Piece" } }
}
class Queen : Piece {
override var description: String { get { return "Queen" } }
}
struct Coords : Printable {
let column: Int
let row: Int
init(_ column: Int, _ row: Int) {
self.column = column
self.row = row
}
var description: String { get { return "Coords(\(column), \(row))" } }
}
struct GameBoard {
var board: [[Piece?]]
init() {
board = []
for _ in 1...8 {
board.append(Array<Piece?>(count: 8, repeatedValue:nil))
}
}
subscript(c: Coords) -> Piece? {
get {
return board[c.column][c.row]
}
set (newValue) {
board[c.column][c.row] = newValue
}
}
}
func testGameBoard() {
var board = GameBoard()
board[Coords(4, 5)] = Queen()
func printSquare(coords: Coords) {
if let p = board[coords] {
println("At \(coords) is a \(p)")
} else {
println("At \(coords) is an empty square")
}
}
printSquare(Coords(4, 5)) // Prints: At Coords(4, 5) is a Queen
printSquare(Coords(4, 6)) // Prints: At Coords(4, 6) is an empty square
}
As long as Queen is a subclass of Piece then there would be no problem. As such:
class Piece {}
class Queen : Piece {}
class Board {
var board : [[Piece?]] =
{ var board : [[Piece?]] = []
for _ in 0..<8 { board.append (Array<Piece?>(count: 8, repeatedValue:nil)) }
return board } ()
subscript (row:Int, col:Int) -> Piece? {
get { return board[row][col] }
set { board[row][col] = newValue }}
}
and then use as:
23> let board = Board()
24> b[0,4] = Queen()
25> b[7,4] = Queen()
26> b
$R0: Board = {
board = 8 values {
[0] = 8 values {
[0] = nil
[1] = nil
[2] = nil
[3] = nil
[4] = Some
[5] = nil
[6] = nil
[7] = nil
} ...